【问题标题】:Annotated form validation - conversion failed custom message带注释的表单验证 - 转换失败的自定义消息
【发布时间】:2013-10-05 15:54:23
【问题描述】:

我正在分析 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";            
    }
}

【问题讨论】:

  • 请展示你的观点。
  • 这是公开的 github 示例,我在帖子开头粘贴了链接。这是 form.jsp 的确切视图:link

标签: spring spring-mvc


【解决方案1】:

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

绑定错误的代码是typeMismatch。因此,您可以将其添加到您的消息属性中:

typeMismatch.birthDate = Invalid birth date format.

检查 JavaDoc 中的 DefaultMessageCodesResolverDefaultBindingErrorProcessor 以了解 Spring 的错误代码解析是如何工作的。

【讨论】:

  • 在我的 servlet-context.xml 我把这个:<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="messages" /> </bean> 在 messages.properties 添加了这一行,正如你所建议的那样:typeMismatch.birthDate 没有任何反应
  • 你一定是做错了什么。刚刚自己克隆了项目,添加了消息源+消息,它就可以工作了。你的messages.properties 文件在哪里?
  • 你是对的。无意中我把它放在了 src/main/webapp 文件夹中。现在我将它移到 src/main/resources 中,它就像一个魅力。谢谢!!
【解决方案2】:

你使用了错误标签吗? 您可以在验证注释中使用消息属性。 喜欢这里:

@NotEmpty(message = "serverIP 不能为空") 私有字符串服务器IP;

【讨论】:

  • 此错误不是来自验证注释,而是来自 Spring DataBinder,因此验证注释的任何更改都不会影响其消息。
猜你喜欢
  • 1970-01-01
  • 2015-02-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-28
  • 2018-06-08
  • 1970-01-01
  • 2015-11-29
  • 2021-04-20
相关资源
最近更新 更多