Spring-MVC: we need the simplest example of processing, binding and validating a form

I have a form:

<form action="/processform"> <input name="firstname" value="john" /> <input name="lastname" value="doe" /> </form> 

I have a Person object:

 public class Person { private String firstname; private String lastname; // ... getters & setters ... } 

I want to get this data, perform a check on it and send it to the data warehouse.

How do I write a controller for this? I understand that I can pass parameters as request parameters, but I think that the “right” way to do this somehow binds the data from the form to the Person object, and then receives this Person object in the controller and calls the Validate object that is configured to receiving a Person object.

After long readings, this step confused me. Can someone show me what it takes to “bind” the data, “check” (for example, the validator) and “process” the data (for example, the controller and, in particular, what is passed to it as parameters)?

+7
java spring-mvc validation data-binding
source share
2 answers

Here was the answer that I was looking for, I did not understand that Spring, by default, will take all the parameters from the form view (such as "firstname" and "lastname") and can create an object for you by calling the setter methods of these parameters.

Controller:

 @Controller public class MyFormProcessor { @RequestMapping("/formsubmit") public String handleForm(@Valid Person person, BindingResult errors, Map<String,Object> model){ // ...handle form... } } 

Spring essentially does the following magic before handleForm for this request (obviously, in a more extensible way than I'm picturing for this simple example):

 Person person = new Person(); person.setFirstname( request.getParameter("firstname") ); person.setLastname( request.getParameter("lastname") ); handleForm(person, anErrorsObject, new Model()); 

For verification, you can either create your own validator (which I don’t mention anything about), or if you include the Hibernate Validator in the classpath, then you can annotate the Person class (example below) and when you add the @Valid annotation, as I described in the example above, the Hibernate validator will check the class based on these annotations and send any errors to the error object (the BindingResult object is an extension of Springs Errors ), and for simple examples, the Errors object is an interesting component).

The grounded annotated Persons class for JSR-303 (for use with the @Valid option):

 public class Person { @NotNull @Size(min=3, max=20) private String firstname; @NotNull @Size(min=3, max=20) private String lastname; // ... getters & setters ... } 
+12
source share

Spring contains a complete tutorial that shows you all the aspects you need. This is called the "Petclinic." You can check this out:

git https://github.com/SpringSource/spring-petclinic

+2
source share

All Articles