Wednesday, July 6, 2011

SPRING - Validators for SimpleFormController

Spring Framework provides validation mechanisms to validate the inputs provided to the simple form controller. The validation happens before hitting the controller and Spring Framework takes care of displaying the error message on the same web page.


1. Implement the validation code that validates the bean object.


package com.mybusiness.blueportal.validators;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.mybusiness.blueportal.beans.User;
public class UserSubmitValidator implements Validator {


public boolean supports(Class<?> clazz) {
return User.class.equals(clazz);
}


public void validate(Object command, Errors errors) {


User user = (User) command;


if (user.getFirstName() == null
|| user.getFirstName().trim().length() == 0) {


errors.rejectValue("firstName", "firstName.error",
"First Name is invalid");
}
}
}

The errors.rejectValue() is used to tell the Spring Framework what error to display and for which field in the web page.

firstName: Specifies the field on the web page.
firstName.error: Specifies the error code that Spring Framework looks up in the properties file, if configured.
First Name is invalid: This is the default message that will be displayed when the error code is not present in the properties.

2. Add the validation to the Spring Configuration.

<bean class="com.mybusiness.blueportal.validators.UserSubmitValidator"
id="userValidator"></bean>

<bean name="/userSubmit.do"
class="com.mybusiness.blueportal.controllers.UserSubmitController">
<property name="sessionForm" value="true" />
<property name="commandName" value="user" />
<property name="commandClass" value="com.mybusiness.blueportal.beans.User" />
<property name="formView" value="UserSubmit" />
<property name="successView" value="UserSubmitSuccess" />
<property name="validator" ref="userValidator"></property>
</bean>

3. Add the validation to the web page.

<form:form method="POST" commandName="user">

First Name : <form:input path="firstName" />
<form:errors path="firstName" />
<br>
Last Name : <form:input path="lastName" />
<br>
Age : <form:input path="age" />
<br>
Hobbies : <form:checkbox path="hobbies" value="Sports" label="Sports" />
<form:checkbox path="hobbies" value="Studies" label="Studies" />
<br>
<input type="submit" value="Submit" />
</form:form>


No comments:

Post a Comment