带注释的表单验证 - 转换失败的自定义消息

时间:2013-09-29 20:51:35

标签: spring spring-mvc

我正在分析spring-mvc-showcase示例项目(spring-mvc-showcase github)。当我点击错误的日期格式(屏幕截图上的出生日期字段)时,在JSP页面上显示验证响应的方式会感到困惑。如何使用某些自定义消息使其更加用户友好,而没有那些ConversionFailedException详细信息?

截图:

enter image description here

应用注释驱动的验证。下面是来自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";            
    }
}

2 个答案:

答案 0 :(得分:8)

请注意,您正在使用绑定错误。在执行实际的JSR-303验证之前很久就会抛出它们,它们会覆盖失败字段的JSR-303约束违规。

绑定错误的代码是typeMismatch。因此,您可以将此示例添加到邮件属性中:

typeMismatch.birthDate = Invalid birth date format.

检查JavaDoc是否为DefaultMessageCodesResolverDefaultBindingErrorProcessor,以了解Spring的错误代码解析方式是如何工作的。

答案 1 :(得分:-1)

你使用过错误标签吗? 您可以在验证注释中使用message属性。 像这里:

@NotEmpty(message =“serverIP不能为空”)     private String serverIP;

相关问题