Spring 3 MVC validation BindingResult doesn't contain any errors

Posted by Travelsized on Stack Overflow See other posts from Stack Overflow or by Travelsized
Published on 2010-06-18T14:54:11Z Indexed on 2010/06/18 15:03 UTC
Read the original article Hit count: 210

I'm attempting to get a Spring 3.0.2 WebMVC project running with the new annotated validation support. I have a Hibernate entity annotated like this:

@Entity
@Table(name = "client")
public class Client implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Basic(optional = false)
    @Column(name = "clientId", nullable = false)
    @NotEmpty
    private Integer clientId;

    @Basic(optional = false)
    @Column(name = "firstname", nullable = false, length = 45)
    @NotEmpty
    @Size(min=2, max=45)
    private String firstname;

    ... more fields, getters and setters
}

I've turned on mvc annotation support in my applicationContext.xml file:

<mvc:annotation-driven />

And I have a method in my controller that responds to a form submission:

@RequestMapping(value="/addClient.htm")
public String addClient(@ModelAttribute("client") @Valid Client client, BindingResult result) {
    if(result.hasErrors()) {
        return "addClient";
    }
    service.storeClient(client);
    return "clientResult";
}

When my app loads in the server, I can see in the server log file that it loads a validator:

15 [http-8084-2] INFO org.hibernate.validator.util.Version - Hibernate Validator 4.0.2.GA

The problem I'm having is that the validator doesn't seem to kick in. I turned on the debugger, and when I get into the controller method, the BindingResult contains 0 errors after I submit an empty form. (The BindingResult does show that it contains the Client object as a target.) It then proceeds to insert a record without an Id and throws an exception. If I fill out an Id but leave the name blank, it creates a record with the Id and empty fields.

What steps am I missing to get the validation working?

© Stack Overflow or respective owner

Related posts about hibernate

Related posts about validation