Abstract
Spring Framework Article... hmm... yummy.
Validation is a complex issue and needs to be explained as a simple concept to make learning it easier and faster. Today, I am working on some very important European Comission application using Spring and I have to validate some form input using Spring. So I think I'll write an article about it, while I am at it.
First things first
In my opinion validation is business logic more than it's not, and it should be specified in a adnotated way. But, that's not how Spring works and that's not how any Enterprise Framework views it. Validation in Spring "is usable in every layer of an application". Along with validation comes Data binding. This is useful for binding user input to the the objects that process user input of an application in a dynamic way.
In my application I am validating data in the MVC framework, and so I'll use the validation package which contains both Validator and DataBinder interfaces. Besides these the BeanWrapper and PropertyEditors also exists. The concept of a PropertyEditor is part of the JavaBeans specification. The BeanWrapper wraps a bean and performs actions on it, sets and retrieves properties and pretty much can manipulate the bean (that is a JavaBean). But for starters, I will just validate some data that comes from a form submitted within a view.
The Controller
I wrote a controller and a view (a JSP containing an input form) and I made it all work. The user requests a htm resource, completes some fields with data and submits the page. The DispatcherServlet has been configured (by me of course) to map the resource to a controller, whose type is CancellableFormController. When the user loads the resource executes a HTTP GET request, the DispatcherServler maps to my associated controller and returns a view - the JSP. The user then completes the form and submits it executing a HTTP POST request this time. The DispatcherServlet maps to the same controller but this time, the controler returns the succesful view, another view. What I want is to hook a validator in the controller so that data received from the submission is validated and eventually if invalid, the same view is displayed (not the success one) and possibly this view should also display the invalidity errors this time.
The Validator
Easy as pie, all I have to do is create a class that implements Validator and inject it into the controller (in the beans configuration xml file). The validator is easy to implement, and it does it's job well. The actual thing is how should the JSP page become aware of the errors? Because it's the same old JSP page used for the initial submission. Well, it has to have some code that queris the "errors" object. How can one know that this object should be queried?
