如何将字符串从表单输入(如果是 easyui-datetimebox)转换为 Controller 中对象中的日历属性,由 Spring 自动绑定(bind)?
我读过 http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/validation.html但我在那儿找不到任何恰到好处的内容。
JSP:
<input id="DeadLineDate"
class="easyui-datetimebox"
name="DeadLineDate"
value="${SessionDeadLineDate}"
data-options="formatter:myformatter,
parser:myparser
/>
提交时,Spring验证抛出错误:
Failed to convert property value of type java.lang.String to required type java.util.Calendar for property DeadLineDate; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Calendar] for property DeadLineDate: no matching editors or conversion strategy found.
附言: Spring 3
编辑:添加 Controller 的方法来执行操作:
@Controller
@RequestMapping("/project/MaintainProjectFrm")
@SessionAttributes({"project","SessionDeadLineDate"})
public class MaintainProjectController {
/* ... many methods... */
@RequestMapping(params = "update", method = RequestMethod.POST, produces={"text/plain; charset=UTF-8"})
public String update(@ModelAttribute("project") Project project,
BindingResult result,
SessionStatus status,
ModelMap model,
HttpServletRequest req,
HttpServletResponse resp) throws IOException {
projectValidator.validate(project, result);
if (result.hasErrors()) {
//has errors, in this case, that one shown in text above, which is rendered again in view (JSP)
return "/project/MaintainProjectFrm";
} else {
try{
mpService.updateProject(project);
}
catch(Exception e){
resp.setStatus(500);
resp.getWriter().write("Error updating project: " + e.getMessage());
return "/project/MaintainProjectFrm";
}
status.setComplete();
}
}
/* ... yet other methods ... */
}
最佳答案
我假设您的 Project
类具有字段 DeadLineDate
(字段应以小写字符开头)。
像这样用@DateTimeFormat
注释
@DateTimeFormat(pattern = "yyyy/MM/dd") // or whatever pattern you want
private Calendar DeadLineDate;
然后您的客户端将需要发送适当的模式。
关于java - Spring:将字符串从 View 转换为日历对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21260209/