首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Spring MVC中,无法使用Jackson @JsonFormat将输入绑定到日期字段

在Spring MVC中,无法使用Jackson @JsonFormat将输入绑定到日期字段
EN

Stack Overflow用户
提问于 2016-07-12 08:26:26
回答 0查看 2.3K关注 0票数 1

我有一个使用Spring MVC的应用程序,它与REST服务交互。UI有一个典型的使用JSP的表单输入。

有一个我希望允许用户修改和持久化的对象,它包含一个日期字段:

代码语言:javascript
复制
public class TheObject {

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "PST")
    private Date myDate;
    .
    .
    .
}

在UI上,这被绑定到一个输入:

代码语言:javascript
复制
<form:input path="myDate"/>

因此,在我的控制器中,当我发布表单并在输入框中输入正确的"yyyy-MM-dd“字符串时,我得到的字段为null,并出现绑定错误。控制器方法如下所示

代码语言:javascript
复制
@RequestMapping(value = "thePath", method = RequestMethod.POST)
public String postMyForm( @Valid @ModelAttribute final theObject backingModel, final BindingResult result, final Model model,
        final HttpServletRequest request) throws Exception {

        //Breakpoint here to check the binding
}

如果我查看那里的BindingResult,我会看到一个错误,内容如下:

代码语言:javascript
复制
Field error in object 'backingModel' on field 'theDate': rejected value [2016-07-07]; codes [typeMismatch.backingModel.theDate,typeMismatch.theDate,typeMismatch.java.util.Date,typeMismatch]; 
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [backingModel.theDate,theDate]; 
arguments []; default message [theDate]]; 
default message [Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for property 'theDate'; 
nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@com.fasterxml.jackson.annotation.JsonFormat java.util.Date] for value '2016-07-07'; nested exception is java.lang.IllegalArgumentException]

如果我去掉@Valid,我会得到一个带有相同消息的异常。

我应该如何绑定它呢?

如果我用@DateTimeFormat(pattern = "yyyy-MM-dd")替换注释,那么绑定就可以正常工作。但是这个对象需要Jackson注释。

EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38318183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档