2015-09-26 131 views
1

我想验证我的表单域。我遵循this tutorial。我只想显示我给出的错误消息(不需要使用MessageResource,但是pojo内部是硬编码的消息)。我使用Hibernate和spring验证作为上面的教程使用。这是我的pojo,用作带有验证注释的模型属性。鉴于错误消息不显示在春天表单验证

import javax.validation.constraints.NotNull; 
import org.hibernate.validator.constraints.Email; 
import org.hibernate.validator.constraints.NotEmpty; 

public class User { 

    @NotNull(message="username cannot be empty") 
    private String username; 
    @NotEmpty @Email(message="e mail cannot be empty") 
    private String email; 
    (... encapsulated getters and setter..) 

这是我的JSP。

<form:form action="register" method="post" commandName="userForm"> 
      <table border="0"> 
       <tr> 
        <td colspan="2" align="center"><h2>Spring MVC Form Demo - Registration</h2></td> 
       </tr> 
       <tr> 
        <td>User Name:</td> 
        <td><form:input path="username" /> 
        <form:errors path="username"></form:errors> 
        </td> 

       </tr> 
       <tr> 
        <td>E-mail:</td> 
        <td><form:input path="email" /> 
        <form:errors path="email"></form:errors> 
        </td> 
       </tr> 
       <tr> 
        <td colspan="2" align="center"><input type="submit" value="Register" /></td> 
       </tr> 
      </table> 
     </form:form> 

这里是我的控制器:

@RequestMapping(method = RequestMethod.POST) 
    public String processRegistration(@ModelAttribute("userForm") @Valid User user 
             ,BindingResult result 
             ,Map<String, Object> model) { 

     if(result.hasErrors()){ 
        return "registration"; 
     } 
return "profile"; 

我的pom.xml里面,

<dependency> 
    <groupId>javax.validation</groupId> 
    <artifactId>validation-api</artifactId> 
    <version>1.1.0.Final</version> 
</dependency> 
<dependency> 
    <groupId>org.hibernate</groupId> 
    <artifactId>hibernate-validator</artifactId> 
    <version>5.0.1.Final</version> 
</dependency> 

当有场错误,页面仅显示默认的错误是may not be empty。我如何设置给定的错误消息而不是默认错误?任何人都可以在我的实施中看到任何错误

回答

1

正如你会得到username cannot be empty只有当用户名为空。将其更改为@NotEmpty。仅当电子邮件格式不正确时才会得到e mail cannot be empty。如果电子邮件为空,则会打印默认邮件,因为您尚未将任何邮件附加到电子邮件属性的@NotEmpty。 @桑杰的建议将解决这个问题。

+0

感谢您的回答+解释。有效。 –

1

你能试试这个,看看它是否有效:根据您当前的代码

@NotEmpty(message="username cannot be empty") 
private String username; 

@NotEmpty(message="email cannot be empty") 
@Email(message="email not well formed") 
private String email;