gpt4 book ai didi

java - 在 Spring MVC 中,无法使用 Jackson @JsonFormat 将输入绑定(bind)到日期字段

转载 作者:行者123 更新时间:2023-12-02 03:29:15 26 4
gpt4 key购买 nike

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

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

public class TheObject {

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

在 UI 上,这绑定(bind)到输入:

<form:input path="myDate"/>

因此,在我的 Controller 中,当我发布表单并且在该输入框中输入了正确的“yyyy-MM-dd”字符串时,我得到的字段为 null 并出现绑定(bind)错误。 Controller 方法如下所示

@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,我会收到带有相同消息的异常。

我应该如何绑定(bind)它?

如果我用 @DateTimeFormat(pattern = "yyyy-MM-dd") 替换注释,则绑定(bind)工作正常。但该对象需要 Jackson 注释。

最佳答案

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

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

因此,我会将其作为答案发布,以防其他人遇到此问题(除非有人认为我上面描述的内容确实是不好的做法或其他什么)。

关于java - 在 Spring MVC 中,无法使用 Jackson @JsonFormat 将输入绑定(bind)到日期字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38318183/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com