Saturday, December 19, 2015

Spring Form validation using Spring Validation API

In my previous post "Spring simple form handling" I have describe how to handle simple data mapping in Spring. In this post I will describe how to use Spring validation API to validate model objects and show appropriate errors on views. For this example I will use same project that I had used in previous post. 

Prerequisites 
  1. You should have install java in your PC and set path variable correctly (JAVA_HOME, JRE_HOME)
  2. You should have install Eclipse Java EE LUNA 4.4 IDE or any IDE you preferred (In this post I'm Using Eclipse )
  3. You should have the project which completed on my previous post "Spring simple form handling"

Step 1 Add Spring Validation API dependency 

As the first step lets add the Spring validation API in to project. To do that double click on pom.xml then click on dependencies. Then click on add. Then type "validation-API" and select javax.validation validation-API as below image.



Step 2 Add Spring Validator class

Right click on src folder and add new class call "UserValidator" as below image. Provide seperate package for validator class. Then click on Add button to specify interface which should validaor class implement.  



Type validator on input field and select spring frame work validator as below image. Then click OK.



You will see two methods which we should implement in our validator class as support and validate method. In support method has a parameter which passes the model class and we have to specify whether we are going to validate that or not by returning true or false. So the method implementation should be similar to this one.

public boolean supports(Class<?> className) {

if(className.equals(User.class))
{
return true;
}
return false;
}

Next is validate method which contains how to validate the specified model objects. It requires two parameters first one will be Model object and second one is errors. In validate method first we have to check whether the object is instance of the required model object. In our example it is User object. In below example it check whether user ID has minimum length of 3 characters and user first name has entered. 
Then if the validation fails then error message should be added to errors object with key value. This key value will use to get error message.

public void validate(Object obj, Errors errors) {
if(obj instanceof User)
{
User user=(User)obj;
if(user.getId().length()<3)
{
errors.rejectValue("id", "user.id", "Id should be minimum 3 charactors");
}

if(user.getFirstName().length()<1)
{
errors.rejectValue("firstName", "user.firstName", "First Name can not be blank");
}
}
       }


Step 3 Update controller method

First to use Spring validator we have to initialize validator class when system loaded. To do that we have to develop method similar to below. That should be annotated using  @InitBinder. 

@InitBinder
public void initBinder(WebDataBinder binder)
{
binder.addValidators(new UserValidator());
}

Then in our controller save method we getting data from client side in that method we need to tell that this user model object should be validated. To give that we have to use @Valid annotation in-front of the User model parameter as show in below bolted word. If there are errors then we have to stay on the user view so we have to check whether there are any errors and view newUser JSP. So saveUser controller method should be modified as bellow.

@RequestMapping(value="saveUser", method=RequestMethod.POST )
public String saveUser(@Valid @ModelAttribute User user,Errors errors, Model model)
{
System.out.println(user);

if(errors.hasErrors())
{
List<String> prefContctMethods=new ArrayList<String>();
prefContctMethods.add("E-mail");
prefContctMethods.add("Call");
model.addAttribute("prefContct", prefContctMethods);
List<String> sexType=new ArrayList<String>();
sexType.add("Male");
sexType.add("Female");
model.addAttribute("sexType", sexType);
return "newUser";
}

userService.saveUser(user);
model.addAttribute("users", userService.getMockedUsers());
return "allUsers";
}


Step 4 Error message show in JSP

Now we have generated validator correctly then we have to show the error messages on JSP file. To show errors on JSP files we use springform:errors tag. In that tag we have to use key that we used to add error in to errors object on validate method in UserValidator class.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="springform" uri="http://www.springframework.org/tags/form" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>New User</title>
</head>
<body>

Enter your User details
<spring:url value="/saveUser" var="springUrl"/>
<springform:form action="${springUrl}" method="POST" modelAttribute="user">
<table style="width:100%">
 <tr>
   <td>User ID</td>
   <td>
    <springform:input path="id"/>
<springform:errors path="id"  />
   </td>
 </tr>
 <tr>
   <td>First Name</td>
   <td>
<springform:input path="firstName"/>
<springform:errors path="firstName"  />
</td>
 </tr>
 <tr>
   <td>Last Name</td>
   <td>
<springform:input path="lastName"/>
<springform:errors path="lastName"  />
</td>
 </tr>
 <tr><td><br/>Address Details</td></tr>
 <tr>
   <td>No</td>
   <td>
<springform:input path="address.no"/>
</td>
 </tr>
 <tr>
   <td>Street</td>
   <td>
<springform:input path="address.Streat"/>
</td>
 </tr>
 <tr>
   <td>City</td>
   <td>
<springform:input path="address.city"/>
</td>
 </tr>  
 <tr>
   <td>Area</td>
   <td>
<springform:input path="address.area"/>
</td>
 </tr>  
 <tr>
   <td>Country</td>
   <td>
<springform:input path="address.country"/>
</td>
 </tr>      
 <tr>
   <td><br/>Preffered Contact Methods</td>
   <td>
<springform:select path="preferredContactMethod" items="${prefContct}"></springform:select>
</td>
 </tr>      
 <tr>
   <td>Gender</td>
   <td>
<springform:radiobuttons id="radio" items="${sexType}" path="sex"/>
</td>
 </tr>      

</table>

<button type="submit"> Submit</button>
</springform:form>

</body>
</html>


Go to Add User link (http://localhost:8080/SpringFirstWeb/addUser). Then do not enter Id and  enter any 3 words in first name and click submit. If You follow the tutorial correctly then you should see following error messages.






You can access this project on GIT hub repository location using following URL https://github.com/NirmalBalasooriya/SpringFormValidation We have completed project with Spring Validation API and in my future post I will add some advanced features of Spring framework in upcoming posts.

No comments:

Post a Comment