Spring annotations @ModelAttribute and @Valid

vdenotaris picture vdenotaris · Mar 26, 2014 · Viewed 26.6k times · Source

What are the advantages of using @ModelAttribute and @Valid?

Which are the differences?

Is it possible to use them together?

Answer

CodeChimp picture CodeChimp · Mar 26, 2014

@ModelAttribute is used to map/bind a a method parameter or method return type to a named model attribute. See @ModelAttributes JavaDoc. This is a Spring annotation.

@Valid is an annotation that marks an object for JSR-303 bean validation. See @Valids JavaDoc. It is part of JavaEE 6, but I think Hibernate has an earlier implementation that most people use instead.

The advantage of using @ModelAttribute is that you can map a form's inputs to a bean. The advantage of @Valid is that you can utilize JSR-303 bean validation to ensure that the bean that is made is validated against some set of rules.

Yes you can use @ModelAttribute and @Valid together.

The best way to transfer data from a form (sic View) to the a Model object is to follow the typical/traditional MVC design pattern using Spring. My personal preferred way is to have a form in a JSP with Spring JSTL <form:*> tags, with a modelAttribute set. On the Controller, have a handler to accept the POST from the form that has a matching @ModelAttribute that is a bean that represents the form's input. I would then pass that "Form Bean" to a service layer to do some things, including translating the "Form Bean" into any models if needed (not necessary if the form is creating your model objects directly) and saving/updating/etc via a DAO. This is but one way to do things, but it's probably the bulk of what I do with Spring in my day-to-day job.

I would highly recommend reading the Spring reference materials and following the tutorials. The reference materials are very well written, easy to follow, and includes lots of examples on the various ways you can do things in Spring, and there are usually quite a few options on how you do things in Spring.