2013-09-29 81 views
1

我在分析spring-mvc-showcase示例项目(spring-mvc-showcase github)。当我点击不正确的日期格式(截图上的出生日期字段)时,与在JSP页面上呈现验证响应的方式相混淆。如何使用一些自定义消息使用户更友好,但没有ConversionFailedException细节?注释表单验证 - 转换失败的自定义消息

截图:

enter image description here

注解驱动验证应用。下面是代表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";    
    } 
} 
+0

请显示您的看法。 –

+0

这是公共github的例子,我粘贴链接在我的帖子的开头。这里是确切的看法form.jsp: [链接](https://github.com/spring-projects/spring-mvc-showcase/blob/master/src/main/webapp/WEB-INF/views/form。 jsp) – shx

回答

8

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

绑定错误的代码是typeMismatch。为DefaultMessageCodesResolverDefaultBindingErrorProcessor

typeMismatch.birthDate = Invalid birth date format. 

检查的JavaDoc发现Spring的错误代码分辨率是如何工作的:所以你可以例如添加到您的邮件属性。

+0

在我的servlet-context.xml中,我把这个: ' ' 在messages.properties加入此行,为您推荐: 'typeMismatch.birthDate' 什么也没有发生 – shx

+0

你必须做一些错误的。我自己克隆了这个项目,添加了消息来源+消息并且它可以工作。你的'messages.properties'文件位于哪里? –

+0

你说得对。无意中,我把它放在src/main/webapp文件夹中。现在我把它移到了src/main/resources中,它就像一个魅力一样。谢谢!! – shx

0

您使用了错误标签吗? 您可以在验证注释中使用消息属性。 like here:

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

+1

此错误不是来自验证注释,而是来自Spring DataBinder,因此不会更改验证注释将影响其消息。 – Jules