如何使DateTimeFormat与Spring MVC一起使用?
问题内容:
我有一个看起来像这样的控制器方法:
@RequestMapping(headers = "Accept=application/json;charset=utf-8", value = "/test", method = RequestMethod.GET)
@ResponseBody
public Blah test(@ModelAttribute MyObject parms, HttpServletRequest request) throws Exception {
// blah blah
}
MyOBject看起来像这样:
public class MyObject{
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Calendar someDate;
// blah blah setters getters
当我像这样通过浏览器调用此方法时:
http://localhost:8080/blah/test?someDate=2011-07-11T21%3A28%3A59.564%2B01%3A00
我收到错误400-错误的请求。
我一直尝试为someDate使用各种不同的值(总是使用URL编码器来编码特殊字符),但没有任何效果。我尝试过的所有方法(URL之前的编码):
2000-10-31 01:30:00.000-05:00
2011-07-11T21:28:59.564 + 01:00
2014-04-23T13:49:28.600Z
我知道日期不匹配,我只是想让Spring将这个该死的日期解析为该Calendar对象!(尽管实际上我更喜欢它是一个java.sql.Timestamp,但这可能更难完成)
我该怎么做呢?
我写的日期写错了吗?我是否对ModelAttribute中的属性使用了错误的注释(请注意,我还有许多其他参数,因此我将它们捆绑在ModelAttribute对象中,不想使用@RequestParm)
在日志文件中显示的错误:
Field error in object 'myObject' on field 'someDate': rejected value [2011-07-11T21:28:59.564+01:00]; codes [typeMismatch.myObject.someDate,typeMismatch.someDate,typeMismatch.java.util.Calendar,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [myObject.someDate,someDate]; arguments []; default message [someDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Calendar' for property 'someDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @org.springframework.format.annotation.DateTimeFormat java.util.Calendar for value '2011-07-11T21:28:59.564+01:00'; nested exception is java.lang.IllegalArgumentException: Unable to parse '2011-07-11T21:28:59.564+01:00']
问题答案:
这个
'2011-07-11T21:28:59.564+01:00'
值不正确,因为预期格式为
yyyy-MM-dd'T'HH:mm:ss.SSSZ
您不能:
在+0100
时区内部设置偏移量。
您必须将url编码错误。