我正在分析 spring-mvc-showcase 示例项目(spring-mvc-showcase github)。当我点击不正确的日期格式(屏幕截图上的出生日期字段)时,对 JSP 页面上显示验证响应的方式感到困惑。在没有那些 ConversionFailedException 详细信息的情况下,如何使用一些自定义消息使其对用户更加友好?
截屏:
应用注释驱动的验证。下面是代表birthDate 字段的bean 类的代码段。
FormBean.java
@DateTimeFormat(iso=ISO.DATE)
@Past
private Date birthDate;
负责表单提交的方法:
FormController.java
@RequestMapping(method=RequestMethod.POST)
public String processSubmit(@Valid FormBean formBean, BindingResult result,
@ModelAttribute("ajaxRequest") boolean ajaxRequest,
Model model, RedirectAttributes redirectAttrs) {
if (result.hasErrors()) {
return null;
}
// Typically you would save to a db and clear the "form" attribute from the session
// via SessionStatus.setCompleted(). For the demo we leave it in the session.
String message = "Form submitted successfully. Bound " + formBean;
// Success response handling
if (ajaxRequest) {
// prepare model for rendering success message in this request
model.addAttribute("message", message);
return null;
} else {
// store a success message for rendering on the next request after redirect
// redirect back to the form to render the success message along with newly bound values
redirectAttrs.addFlashAttribute("message", message);
return "redirect:/form";
}
}