Search code examples
javaspringtomcathibernate-validator

How to pass error message from bean to form in Spring


I have simple application where I am using validation (which works perfectly) however I have issues passing error message back to form. In examples I have seen it looks like it is "magically" passed back to form without manually setting any attribute or whatsoever.

This is my controller code :

@RequestMapping(value = "/createMember", method = RequestMethod.GET)
public ModelAndView showContacts() {

    return new ModelAndView("createMember", "command", new Member());
}

@RequestMapping(value = "/createMember", method = RequestMethod.POST)
public ModelAndView addContact(@ModelAttribute("member")
                        @Valid Member member, BindingResult result) {

    if(result.hasErrors()) {
        return new ModelAndView("createMember", "command", member);
    }     
    mba.addMember(member);         
    return getPages();
}   

And this is my createMember.jsp :

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>
<head>

<script src="<c:url value="/resources/core/jquery.1.10.2.min.js" />"></script>
<script src="<c:url value="/resources/core/jquery.autocomplete.min.js" />"></script>
<link href="<c:url value="/resources/core/main.css" />" rel="stylesheet">

</head>
<body>
<form:form method="post" action="createMember.html">

    <table>
    <tr>
        <td><form:label path="firstName">First Name</form:label></td>
        <td><form:input path="firstName" value="${member.firstName}" /></td> 
        <form:errors path="firstName" cssclass="error"></form:errors>
    </tr>    
    <tr>
        <td><form:label path="lastName">Last Name</form:label></td>
        <td><form:input path="lastName" value="${member.lastName}" /></td>
        <form:errors path="lastName" cssclass="error"></form:errors>
    </tr>
    <tr>
        <td><form:label path="email1">Email</form:label></td>
        <td><form:input value="${member.email1}" path="email1" /></td>
        <form:errors path="email1" cssclass="error"></form:errors>
    </tr>

    <tr>
        <td colspan="2">
            <input type="submit" value="Add Contact"/>
        </td>
    </tr>
</table>  

</form:form>

<a href="${pageContext.servletContext.contextPath}"> Back to main page </a> 

</body>
</html>

I am using Spring 3.2.2, Tomcat 7, hibernate-validator

Validation class :

import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
public class Member {

    private int memberID;
    private int gender;

    @Size(min=2, max=30)
    private String firstName;

    @Size(min=2, max=30)
    private String lastName;

    @NotEmpty @Email
    private String email1;

    //...getters and setters here
}

Solution

  • Try @ModelAttribute("command") instead of @ModelAttribute("member") in your controller class.