首页 文章

如果无效日期,Spring mvc Joda Datetime转换器会失败

提问于
浏览
4

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

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显然会在我的验证器类之前命中转换器,并将填充我的错误消息并显示完整错误

Failed to convert property value of type java.lang.String to required type org.joda.time.DateTime for property sampleDate; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "asdf" from type java.lang.String to type org.joda.time.DateTime; nested exception is java.lang.IllegalArgumentException: Invalid date

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

有没有办法获取异常消息“无效的日期”而不是显示的整个事情?

1 回答

  • 2

    您应该使用文件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>
    

相关问题