如果无效日期,Spring mvc Joda Datetime转换器会失败 [英] Spring mvc Joda Datetime converter fail if invalid date
问题描述
我有一个域对象,我希望从包含Joda DateTime的JSP映射:
I have a domain object that i want to have mapped from JSP that contains a Joda DateTime:
public beanClass{
private Long id;
@DateTimeFormat
private DateTime start;
getters and setters...
}
我有以下转换器在Spring中注册:
I have the following converter registered with 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 obviously hits the converter before my validator class and will populate my error messages with the full error
无法将java.lang.String类型的属性值转换为所需类型org.joda。属性sampleDate的time.DateTime;嵌套异常是org.springframework.core.convert.ConversionFailedException:无法将值asdf从类型java.lang.String转换为类型org.joda.time.DateTime;嵌套异常是java.lang.IllegalArgumentException:无效日期
我想要的是从异常中获取无效日期消息。
What I want is to get the "Invalid date" message from the exception.
有没有办法让异常消息无效的日期而不是显示的全部内容?
Is there a way to get the exception message "Invalid date" instead of the whole thing to display?
推荐答案
您应该使用文件messages.properites来声明特定信息:
You should use file messages.properites to declare specific information:
typeMismatch.java.util.Date = Invalid date
当然,您应该在spring-context.xml中提供有关此文件的信息
Of course you should provide information about this file in your 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>
这篇关于如果无效日期,Spring mvc Joda Datetime转换器会失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!