我正在分析spring-mvc-showcase示例项目(spring-mvc-showcase github)。当我输入错误的日期格式(屏幕截图上的“出生日期”字段)时,与验证响应在JSP页面上呈现的方式相混淆。如何在不使用那些ConversionFailedException详细信息的情况下使用一些自定义消息使它更加用户友好?
屏幕截图:
应用了注释驱动的验证。下面是来自bean类的代码段,它代表birthDate字段。
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";
}
}
请注意,您正在此处处理绑定错误。它们在实际的JSR-303验证执行之前就已抛出,并且它们覆盖了失败字段的JSR-303约束违规。
绑定错误的代码为typeMismatch
。因此,您可以在邮件属性中添加以下示例:
typeMismatch.birthDate = Invalid birth date format.
检查JavaDoc中的DefaultMessageCodesResolver和DefaultBindingErrorProcessor以发现Spring的错误代码解析的工作方式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句