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 receive this data, perform validation on it, and post it to a datastore.
How do I write a controller to do this? I understand that I could pass the parameters in as request parameters, but I think the "proper" way to do this is somehow bind the data from the form to the Person object and then receive that Person object in the controller and call a Validate object that is configured to receive the Person object.
After much reading, this step has confounded me. Can someone show me what is needed to "bind" the data, "validate" (e.g. a validator), and "process" the data (e.g. the controller, and in particular what gets passed to it as parameters)?
Here was the answer I was looking for, I didn't understand that Spring, by default, will take all of the parameters from the form submission (such as "firstname" and "lastname") and can create the object for you by calling the setter methods of these parameters.
The controller:
@Controller
public class MyFormProcessor {
@RequestMapping("/formsubmit")
public String handleForm(@Valid Person person, BindingResult errors, Map<String,Object> model){
// ...handle form...
}
}
Spring is essentially doing the following magic before calling handleForm
for this request (obviously in a more extendable way than I depict for this simple example):
Person person = new Person();
person.setFirstname( request.getParameter("firstname") );
person.setLastname( request.getParameter("lastname") );
handleForm(person, anErrorsObject, new Model());
For validation you can either create your own validator (which I won't mention anything about here), or if you include Hibernate Validator in the classpath, then you can annotate the Person
class (example below) and when you add the @Valid
annotation as I depicted in the example above the Hibernate validator will validate the class based on those annotations and post any errors to the error object (a BindingResult
object is an extension of Springs' Errors
, and for simple examples the Errors
object is the interesting component).
JSR-303 validation annotated Person class (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 ...
}
Spring has a complete tutorial showing every aspect that you need. It's called "Petclinic". You can check it out from:
git https://github.com/SpringSource/spring-petclinic
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With