Luk*_*uke 1 java spring jsp spring-mvc jackson
我有一个使用 Spring MVC 与 REST 服务交互的应用程序。UI 具有使用 JSP 的典型表单输入。
我希望允许用户修改和保留一个包含日期字段的对象:
public class TheObject {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "PST")
private Date myDate;
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
在 UI 上,这绑定到一个输入:
<form:input path="myDate"/>
Run Code Online (Sandbox Code Playgroud)
因此,在我的控制器中,当我发布表单并在该输入框中输入了正确的“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
}
Run Code Online (Sandbox Code Playgroud)
如果我查看那里的 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]
Run Code Online (Sandbox Code Playgroud)
如果我取出@Valid,我会收到带有相同消息的异常。
我应该如何绑定它?
如果我用 @DateTimeFormat(pattern = "yyyy-MM-dd") 替换注释,则绑定工作正常。但是该对象需要 Jackson 注释。
所以在发布所有内容后,我意识到我可以添加两个注释并且它有效
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "PST")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date myDate;
Run Code Online (Sandbox Code Playgroud)
因此,我会将其发布为答案,以防其他人遇到此问题(除非有人认为我上面描述的内容非常糟糕或其他任何事情)。
| 归档时间: |
|
| 查看次数: |
2279 次 |
| 最近记录: |