在Spring-MVC中添加自定义错误消息以进行验证

时间:2014-11-19 12:37:59

标签: validation spring-mvc hibernate-validator

我正在使用Spring-MVC,我想在后端进行验证测试。目前我能够执行测试,正确地重定向到链接。但是,如果出现问题,我只能添加自定义错误消息,例如:" Firstname为空"。我尝试使用WEB-INF中的ValidationMessages_en_EN.properties文件,但这也没有帮助。我发布了我的代码,请让我知道我哪里出错:

COntroller:

@Controller
public class PersonController {
 @RequestMapping(value = "/", method = RequestMethod.GET)
    public String listPersons(Model model) {
        Person person = personService.getCurrentlyAuthenticatedUser();
        if(!(person==null)){
            return "redirect:/canvas/list";
        } else {
            model.addAttribute("person", new Person());
         //   model.addAttribute("listPersons", this.personService.listPersons());
            model.addAttribute("notices",new Notes());
            model.addAttribute("canvases",new Canvas());
            return "person";
        }
    }

    @RequestMapping(value= "/person/add", method = RequestMethod.POST)
    public String addPerson(@Valid Person person,BindingResult bindingResult,@ModelAttribute("person") Person p,Model model){
        if(bindingResult.hasErrors()){
            return "redirect:/";
        }
            this.personService.addPerson(p);
            return "redirect:/";
    }

实体:

@Entity
@Table(name="person")
public class Person implements UserDetails{

    private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_USER");

    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "person_seq_gen")
    @SequenceGenerator(name = "person_seq_gen",sequenceName = "person_seq")
    private int id;

    @Valid
    @NotEmpty @Email(message = "username.empty")
    @Column(name = "username")
    private String username;


    @NotEmpty
    @Column(name = "password")
    private String password;


    @Valid
    @Size(min = 2,max = 30,message = "firstName.empty")
    @Column(name = "firstname")
    private String firstName;

    @Valid
    @Size(min = 2,max = 50)
    @Column(name = "secretquestion")
    private String secretquestion;

    @Valid
    @Size(min = 2,max = 500,message = "secretanswer.empty")
    @Column(name = "secretanswer")
    private String secretanswer;

Servlet-Context.xml

<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <beans:property name="basename" value="ValidatorMessages_en_EN.properties"/>
           </beans:bean>

JSP / HTML:

      <c:url var="addAction" value="/person/add" ></c:url>
<form:form action="${addAction}" commandName="person" method="post">
<table>
    <c:if test="${!empty person.username}">
    <tr>
        <td>
            <form:label path="id">
                <spring:message text="ID"/>
            </form:label>
        </td>
        <td>
            <form:input path="id" readonly="true" size="8"  disabled="true" />
            <form:hidden path="id" />
        </td> 
    </tr>
    </c:if>

    <tr>
        <td>
            <form:label path="firstName">
                <spring:message text="FirstName"/>
            </form:label>
        </td>
        <td>
            <form:input path="firstName" />
        </td>
        <td><form:errors path="firstName"/>
    </tr>
    <tr>
        <td>
            <form:label path="username">
                <spring:message text="Email"/>
            </form:label>
        </td>
        <td>
            <form:input path="username" />
        </td>
        <td><form:errors path="username"/>
    </tr>
    <tr>
        <td>
            <form:label path="password">
                <spring:message text="Password"/>
            </form:label>
        </td>
        <td>
            <form:input path="password" />
        </td>
        <td><form:errors path="Password"/>
    </tr>

    <tr>
    <td>
        <form:label path="secretquestion">
            <spring:message text="secretquestion"/>
        </form:label>
    </td>
    <td>
        <form:input path="secretquestion" />
    </td>
        <td><form:errors path="secretquestion"/>
    </tr>


    <tr>
        <td>
            <form:label path="secretanswer">
                <spring:message text="secretanswer"/>
            </form:label>
        </td>
        <td>
            <form:input path="secretanswer" />
        </td>
        <td><form:errors path="secretanswer"/>
    </tr>

POM.xml:

 <!-- Validation -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.3.1.Final</version>
        </dependency>

Messages.properties:

firstName=firstName
Email=Email
Password=password
secretquestion=secretquestion
secretanswer=secretanswer
NotEmpty.person.firstName=firstName is required!
NotEmpty.person.username=Email is required!
NotEmpty.person.password=Password is required!
NotEmpty.person.secretquestion=SecretQuestion is required!
NotEmpty.person.secretanswer=SecretAnswer is required!

Messages_en_US.properties

firstName=firstName
Email=Email
Password=password
secretquestion=secretquestion
secretanswer=secretanswer
NotEmpty.person.firstName=firstName is required!
NotEmpty.person.username=Email is required!
NotEmpty.person.password=Password is required!
NotEmpty.person.secretquestion=SecretQuestion is required!
NotEmpty.person.secretanswer=SecretAnswer is required!

2 个答案:

答案 0 :(得分:2)

<spring:message text="FirstName"/>应该像<spring:message code="FirstName"/>尝试在您的<spring:message />代码中替换文字代码

并将basename值更改为 ValidatorMessages en_US Spring会为您追加

 <beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
         <beans:property name="basename" value="ValidatorMessages"/>
 </beans:bean>

ValidatorMessages_en_US.properties文件夹

中将您的文件归档为resource

答案 1 :(得分:2)

active