In this tutorial, we will learn how to validate the Spring MVC application using the Bean Validation ( JSR 303 Bean Validation). We will develop a Spring MVC Form validation constraints for the FirstName, LastName, Emails fields. Once when the user submits the form the server-side validation will be applied and the corresponding Validation messages will be thrown if any.
This requires two important jar files along with other Spring related jars to be added to lib folder
- hibernate-validator-4.2.0.Final.jar
- validation-api-1.0.0.GA.jar
Before getting into the Validation you should have some basic knowledge of the Spring MVC Form handling, if not please read through my previous Spring MVC Form Handing article.
Folder Structure :
- Create a Dynamic Web Project RegistrationForm and create a package for our src files “com.javainterviewpoint“
- Place the Spring 3 jar files under WEB-INF/Lib
commons-logging-1.1.1.jar
log4j-1.2.16.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar
hibernate-validator-4.2.0.Final.jar
spring-aspects-3.2.4.RELEASE.jar
spring-beans-3.2.4.RELEASE.jar
spring-context-3.2.4.RELEASE.jar
spring-core-3.2.4.RELEASE.jar
spring-expression-3.2.4.RELEASE.jar
spring-web-3.2.4.RELEASE.jar
spring-webmvc-3.2.4.RELEASE.jar
validation-api-1.1.0.Final.jar - Put the index.jsp under the WebContent directory.
- Create the Java classes RegistrationController.java and RegistrationBean.java under com.javainterviewpoint folder.
- Place the SpringConfig-servlet.xml and web.xml under the WEB-INF directory
- View files RegistrationForm.jsp and Success.jsp are put under the sub directory under WEB-INF/Jsp
RegistrationBean.java
package com.javainterviewpoint; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; public class RegistrationBean { @NotEmpty(message="FirstName cannot be empty") @Size(min=1,max=6,message="Size should be between 1 to 6") String firstName; @NotNull @Size(min=1,max=6,message="Size should be between 1 to 6") String lastName; @NotEmpty(message="Email Address cannot be empty") @Email(message="Please enter a valid email address") String email; String profession; @NotEmpty(message="Atleast one hobby has to be selected") String[] hobby; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getProfession() { return profession; } public void setProfession(String profession) { this.profession = profession; } public String[] getHobby() { return hobby; } public void setHobby(String[] hobby) { this.hobby = hobby; } }
In our bean, we have used JSR303 validations annotations like @NotEmpty, @NotNull, @Size, @Email.
- @NotEmpty–> Ensures that the field cannot be left blank.
- @NotNull–> Ensures that the field can be blank.
- @Size –>Defines the acceptable length of the string with min and max attributes.
- @Email –> Ensures that the entered text is a valid email address.
Index.jsp
This is simply a start-up page which redirects the user to our RegistrationForm.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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>Insert title here</title> </head> <body> <a href="displayForm.html">Click here to Register</a> </body> </html>
RegistrationForm.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="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>Insert title here</title> <style> .error { color: #ff0000; } </style> </head> <body> <form:form action="register" method="post" commandName="rb"> <table> <tr><td>First Name</td><td><form:input path="firstName"/></td><td><form:errors path="firstName" cssClass="error"></form:errors></td></tr> <tr><td>Last Name</td><td><form:input path="lastName"/></td><td><form:errors path="lastName" cssClass="error"></form:errors></td></tr> <tr><td>Email</td><td><form:input path="email"/></td><td><form:errors path="email" cssClass="error"></form:errors></td></tr> <tr><td>Profession</td><td><form:select path="profession" items="${professionList}"></form:select></td><td></td></tr> <tr><td>Hobby</td><td><form:checkboxes items="${hobbyList}" path="hobby"/></td><td><form:errors path="hobby" cssClass="error"></form:errors> <tr><td></td><td><input type="submit" value="Register"></td><td></td></tr> </table> </form:form> </body> </html>
In addition to <form:input> tag we could see the <form:errors> tag which will display the validation errors messaages which we will throw after validation.
RegistrationController.java
package com.javainterviewpoint; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class RegistrationController { @ModelAttribute("professionList") public List populateProfessionList() { List professionList = new ArrayList(); professionList.add("Devloper"); professionList.add("Manager"); professionList.add("Architecht"); return professionList; } @ModelAttribute("hobbyList") public List populateHobbyList() { List hobbyList = new ArrayList(); hobbyList.add("Cricket"); hobbyList.add("Football"); hobbyList.add("Hockey"); hobbyList.add("Basketball"); return hobbyList; } @RequestMapping("/dispForm") public String displayForm(Map model) { RegistrationBean rb = new RegistrationBean(); model.put("rb",rb); return "registrationForm"; } @RequestMapping(value="/register",method=RequestMethod.POST) public String processRegistration(@Valid @ModelAttribute("rb") RegistrationBean rb,BindingResult result) { if(result.hasErrors()) { System.out.println(result); return "registrationForm"; } else { System.out.println(result); System.out.println(rb.getFirstName()); System.out.println(rb.getLastName()); System.out.println(rb.getEmail()); System.out.println(rb.getProfession()); System.out.println("Selected Hobby"); if(rb.getHobby()!=null) { for(String val:rb.getHobby()) { System.out.print(val+" "); } } return "Success"; } } }
Whenever Spring encounters @Valid annotation it searches for the validator, as we have used <mvc:annotation-driven> it automatically picks up the validation annotations.Here @Valid annotation tells the spring to validate the RegistrationBean object. We could see that there is one more attribute called BindingResult result, the result holds the result of the validation and errors if any has occurred during validation.
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>SpringConfig</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringConfig</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
Spring Configuration File
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.jackson"></context:component-scan> <mvc:annotation-driven/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/Jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
Success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!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>Insert title here</title> </head> <body> <center><h1>Registration Successful</h1></center> <table align="center" border="1"> <tr> <td>FirstName</td> <td>${rb.firstName}</td> </tr> <tr> <td>LastName</td> <td>${rb.lastName}</td> </tr> <tr> <td>Email</td> <td>${rb.email}</td> </tr> <tr> <td>Profession</td> <td>${rb.profession}</td> </tr> <tr> <td>Hobby</td> <td><c:forEach var="val" items="${rb.hobby}"> <c:out value="${val}"></c:out> </c:forEach></td> </tr> </table> </body> </html>
Run the Application
Deploy and Run the application into your server, your application will be validated as below.
http://localhost:8080/SpringMVC/
Leave a Reply