Wednesday, July 28, 2010

Spring MVC Fast Tutorial: Form Validation

What are we going to build?

User input validation for the new car form.

Validator

This Validator class will validate a Car: 'WEB-INF/src/springmvc/validator/CarValidator.java'

package springmvc.validator;   import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator;   import springmvc.model.Car;   public class CarValidator implements Validator {   	public boolean supports(Class aClass) { 		return Car.class.equals(aClass); 	}   	public void validate(Object obj, Errors errors) { 		Car car = (Car) obj;   		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "model", "field.required", "Required field");   		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "price", "field.required", "Required field"); 		if ( ! errors.hasFieldErrors("price")) { 			if (car.getPrice().intValue() == 0) 				errors.rejectValue("price", "not_zero", "Can't be free!"); 		}		 	} }
  • supports(): declare classes supported by this validator
  • To add an error these parameters are needed:
    • Car field name
    • error message key
    • default message if no message is not found for the key

View

Let's update the view 'jsp/carNew.jsp':

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>   >   >   >New Sponsor>   >     .error {     	color: red;     }   >   >   > 	>New Car>   	 method="post">   		Brand /> 		 path="brand"> 		    items="${brandList}" itemLabel="name" itemValue="id" /> 		> 		 /> />   		Model  path="model" cssClass="error"/> /> 		 path="model"/> /> />   		Price  path="price" cssClass="error"/> /> 		 path="price"/> /> />   		 type="submit" value="Submit">   	> > >

Configuration

We now declare the validator for the URL addCar.html in 'WEB-INF/springmvc-servlet.xml'

     name="/new_car.html" class="springmvc.web.CarNewController">          name="commandClass" value="springmvc.model.Car"/>          name="formView" value="carNew"/>          name="successView" value="list_cars.html"/> 		 name="validator">         	 class="springmvc.validator.CarValidator"/>         >     >

Result

Build (ant) and relaunch Tomcat: http://localhost:8180/springmvc/new_car.html

We can check it's working by entering empty values:

No comments:

Post a Comment