【发布时间】:2014-04-23 18:00:52
【问题描述】:
我有一个如下所示的控制器方法:
@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']
【问题讨论】:
-
如果您将日志转为 DEBUG,Spring 会告诉您问题。
-
你的第一个测试对我有用。
-
它怎么可能对你有用?我将日志文件中的错误添加到我的 OP 末尾(太长,无法发表评论)
-
您使用的是哪个 Spring 版本?如果日期是正确的 URL 编码,这应该可以工作。
标签: java spring spring-mvc