Monday, January 4, 2016

How does Spring MVC provide validation support?

Ref:- http://howtodoinjava.com/2015/03/02/spring-mvc-interview-questions-with-answers/

Spring MVC supports validation by means of a validator object that implements the Validator interface. You need to create a class and implement Validator interface. In this custom validator class, you use utility methods such asrejectIfEmptyOrWhitespace() and rejectIfEmpty() in the ValidationUtils class to validate the required form fields.
@Component
public class EmployeeValidator implements Validator
{
    public boolean supports(Class clazz) {
        return EmployeeVO.class.isAssignableFrom(clazz);
    }
  
    public void validate(Object target, Errors errors)
    {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName""error.firstName""First name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName""error.lastName""Last name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email""error.email""Email is required.");
    }
}
If any of form fields is empty, these methods will create a field error and bind it to the field. The second argument of these methods is the property name, while the third and fourth are the error code and default error message.
To activate this custom validator as a spring managed bean, you need to do one of following things:
1) Add @Component annotation to EmployeeValidator class and activate annotation scanning on the package containing such declarations.
<context:component-scan base-package="com.howtodoinjava.demo" />
2) Alternatively, you can register the validator class bean directly in context file.
<bean id="employeeValidator" class="com.howtodoinjava.demo.validator.EmployeeValidator" />

No comments:

Post a Comment