java - 如何让 DateTimeFormat 与 Spring MVC 一起工作?

标签 java spring spring-mvc

我有一个看起来像这样的 Controller 方法:

@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编码错了

关于java - 如何让 DateTimeFormat 与 Spring MVC 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23251895/

相关文章:

java - Spring MVC 中 REST 响应对象的部分 JSON 序列化

java - 如何在返回对象的 Spring MVC @RestController @ResponseBody 类中响应 HTTP 状态代码?

spring-mvc - 在 Spring 中测试 Controller 时模拟 WebSecurity 依赖项

java - Intellij 显示断点对于我导入的 jar 文件无效,有人知道如何使其有效吗?

java - Camel 泉中的多条内部路线

java - JVM中包含 `@`的代理密码

spring - 做mockMvc测试时使用Mockito注册spring bean

java - 如何使用 Spring Boot 将使用 Postgresql 的 Spring 应用程序部署到 Heroku?

java - 在java中按索引对数组列表的数组列表进行排序

java - 没有用户登录时存储购物车(playframework 疑问)