【问题标题】:Spring mvc Joda Datetime converter fail if invalid date如果日期无效,Spring mvc Joda Datetime 转换器会失败
【发布时间】:2011-09-26 06:16:56
【问题描述】:

我有一个我想从包含 Joda DateTime 的 JSP 映射的域对象:

public beanClass{
  private Long id;

  @DateTimeFormat
  private DateTime start;

  getters and setters...
}

我在 Spring 中注册了以下转换器:

final class StringToJodaDateTimeConverter<S, T> implements Converter<String, DateTime>    {   

  private static final DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy");

  public DateTime convert(String in) {
     try{
        return fmt.parseDateTime(in);
     }catch(Exception e){
        throw new IllegalArgumentException("Invalid date");
     }
   }
}

Spring 显然在我的验证器类之前命中了转换器,并将用完整的错误填充我的错误消息

无法将 java.lang.String 类型的属性值转换为属性 sampleDate 所需的类型 org.joda.time.DateTime;嵌套异常是 org.springframework.core.convert.ConversionFailedException: Unable to convert value "asdf" from type java.lang.String to type org.joda.time.DateTime;嵌套异常是 java.lang.IllegalArgumentException: Invalid date

我想要的是从异常中获取“无效日期”消息。

有没有办法让异常消息“无效日期”而不是全部显示?

【问题讨论】:

    标签: java spring validation


    【解决方案1】:

    你应该使用文件messages.properites来声明具体信息:

    typeMismatch.java.util.Date = Invalid date
    

    当然你应该在你的 spring-context.xml 中提供关于这个文件的信息

      <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
         <property name="basename" value="/WEB-INF/config/messages"/>
         <property name="defaultEncoding" value="UTF-8"/>         
        </bean>
    

    【讨论】:

    • “typeMismatch.java.util.Date = Invalid date”与日期字段有何关系?
    猜你喜欢
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    • 2014-08-08
    • 1970-01-01
    • 2015-01-16
    相关资源
    最近更新 更多