我有一个使用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“字符串时,我得到的字段为null,并出现绑定错误。控制器方法如下所示
@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注释。
https://stackoverflow.com/questions/38318183
复制相似问题