【问题标题】:In Spring MVC, can't bind an input to a date field with a Jackson @JsonFormat在 Spring MVC 中,无法使用 Jackson @JsonFormat 将输入绑定到日期字段
【发布时间】:2016-11-14 01:32:21
【问题描述】:

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

我希望允许用户修改和保留一个包含日期字段的对象:

public class TheObject {

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

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

<form:input path="myDate"/>

因此,在我的控制器中,当我发布表单并在该输入框中输入了正确的“yyyy-MM-dd”字符串时,该字段为空,并且出现绑定错误。控制器方法是这样的

@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,我会看到一条错误消息:

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 注释。

【问题讨论】:

    标签: java spring jsp spring-mvc jackson


    【解决方案1】:

    所以在发布所有内容后,我意识到我可以添加两个注释并且它可以工作

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

    因此,我会将其发布为答案,以防其他人遇到此问题(除非有人认为我在上面描述的内容是非常糟糕的做法或其他任何事情)。

    【讨论】:

    • @DateTimeFormat 将用于模型属性绑定。 @JsonFormat 与该过程无关。 @JsonFormat 将用于 Jackson 序列化。 @DateTimeFormat 与该过程无关。
    • 谢谢!这几乎就是我的结论,没有意识到这两个属性可以一起使用。
    猜你喜欢
    • 2011-04-11
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2022-12-19
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多