当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Spring mvc Joda Datetime converter fail if invalid date

问题描述:

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...

}

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

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

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?

网友答案:

You should use file messages.properites to declare specific information:

typeMismatch.java.util.Date = Invalid date

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>
分享给朋友:
您可能感兴趣的文章:
随机阅读: