Nearby lessons

24 of 35

Spring - Web MVC Data Validation

📌 What You Will Learn
  • Tell client-side and server-side validation apart, and know why you need both
  • Reject a bad field with Spring's Errors object and redisplay the form
  • Apply Validation API annotations and supply the extra jars they require
  • Move validation messages into a properties file instead of hard-coding them

Validating form input in Spring MVC three ways: client-side, server-side with Spring's own Errors object, and declaratively with the Java Validation API annotations — plus how to move the message text out into a properties file.

Data Validations

The process of checking whether the data is valid or not before using data in application Logic is called as Data Validations.

There are two types of Data Validations.

  • Client Side Data Validations
  • Server Side Data Validations

Client Side Data Validations

If we check whether data is valid or not at client browser after entering data in user forms and before submitting form to Server then it is called as Client Side Data Validations.

To perform Client Side data Validations we will use Java Script functions.

Server Side Data Validations

If we check whether the data is valid or not after storing data at server side and before using data in application logic then it is called as Server side Data validations.

To perform Server side data validation we will use JAVA code at server side.

Spring is providing Server side Data validations in the following two ways.

  • By Using Spring provided Error class.
  • By Using Java provided validation annotations

Spring Data Validations By using Spring provided Error class — index.jsp

To provide data validations in this approach we have to use the following approach.

  • Prepare Validator class by implementing "org.springframework.validation.Validator"

interface.

Validator interface contains the following two methods.

a) public boolean supports(Class<?> cls)

It will check whether the command class is right class or not for data validations

on the basis of Class type.

b) public void validate(Object command, Errors errors)

It will include Data Validation logic .

If any Validation error is identified then we have to use rejectValue() method

b) public void rejectValue(String var_Name, String error_Code)

c) Where variable name is a variable in Comand class.

  • Where error_Code is either validation message directly or a key from the

propertirs file which had validationr message.

  • Provide Properties file under src or in a package under properties file with validation messages in the form of key-value pairs.
  • Configure Validator class and Properties file with "messageSource" property under org.springframework.context.support.ResourceBundleMessageSource
  • Display Validation messages in User forms by using <form:errors/> tag.

Example:

Example04
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5<html>
6<head>
7<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<jsp:forward page="reg"/>
12</body>
13</html>
14

Spring Data Validations By using Spring provided Error class — registrationform.jsp

Example05
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
5<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
6<html>
7<head>
8<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
9<title>Insert title here</title>
10<style type="text/css">
11.error{
12color: red;
13font-family: consolas;
14font-style: italic;
15font-weight: bold;
16font-size: large;
17}
18</style>
19</head>
20<body>
21<br><br><br>
22<h2 style="color: red;" align="center">Durga Software Solutions</h2>
23<h3 style="color: red;" align="center">Student Registration Form</h3>
24<form:form method="POST" action="reg" commandName="user">
25<center>
26<table>
27<tr>
28<td>User Name</td>
29<td><form:input path="uname"/></td>
30<td><form:errors path="uname" cssClass="error"/>
31</tr>
32<tr>
33<td>User Password</td>
34<td><form:password path="upwd"/></td>
35<td><form:errors path="upwd" cssClass="error"/>
36</tr>
37<tr>
38<td>User Age</td>
39<td><form:input path="uage"/></td>
40<td><form:errors path="uage" cssClass="error"/>
41</tr>
42<tr>
43<td>User Email Id</td>
44<td><form:input path="uemail"/></td>
45<td><form:errors path="uemail" cssClass="error"/>
46</tr>
47<tr>
48<td>User Mobile No</td>
49<td><form:input path="umobile"/></td>
50<td><form:errors path="umobile" cssClass="error"/>
51</tr>
52<tr>
53<td><input type="submit" value="Registration"/></td>
54</tr>
55</table>
56</center>
57</form:form>
58</body>
59</html>
60

Spring Data Validations By using Spring provided Error class — registrationdetails.jsp

Example06
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5<html>
6<head>
7<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<br><br><br>
12<h2 style="color: red;" align="center">Durga Software Solutions</h2>
13<h3 style="color: red;" align="center">User Registration Details</h3>
14<center>
15<table border="1">
16<tr>
17<td>User Name</td>
18<td>${user.uname}</td>
19</tr>
20<tr>
21<td>User Password</td>
22<td>${user.upwd}</td>
23</tr>
24<tr>
25<td>User Age</td>
26<td>${user.uage}</td>
27</tr>
28<tr>
29<td>User Email Id</td>
30<td>${user.uemail}</td>
31</tr>
32<tr>
33<td>User Mobile No</td>
34<td>${user.umobile}</td>
35</tr>
36</table>
37</center>
38</body>
39</html>
40

Spring Data Validations By using Spring provided Error class — User.java

Example07
JCode Cell
1 
2package com.durgasoft.command;
3 
4public class User {
5private String uname;
6private String upwd;
7private int uage;
8private String uemail;
9private String umobile;
10 
11public String getUname() {
12return uname;
13}
14public void setUname(String uname) {
15this.uname = uname;
16}
17public String getUpwd() {
18return upwd;
19}
20public void setUpwd(String upwd) {
21this.upwd = upwd;
22}
23public int getUage() {
24return uage;
25}
26public void setUage(int uage) {
27this.uage = uage;
28}
29public String getUemail() {
30return uemail;
31}
32public void setUemail(String uemail) {
33this.uemail = uemail;
34}
35public String getUmobile() {
36return umobile;
37}
38public void setUmobile(String umobile) {
39this.umobile = umobile;
40}
41 
42 
43}
44

Spring Data Validations By using Spring provided Error class — UserController.java

Example08
JCode Cell
1 
2package com.durgasoft.controller;
3 
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6 
7import org.springframework.validation.BindException;
8import org.springframework.web.servlet.ModelAndView;
9import org.springframework.web.servlet.mvc.SimpleFormController;
10 
11import com.durgasoft.command.User;
12 
13public class UserController extends SimpleFormController {
14@Override
15protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
16 BindException errors) throws Exception {
17User user = (User)command;
18return new ModelAndView("registrationdetails", "user", user);
19}
20}
21

Spring Data Validations By using Spring provided Error class — UserValidator.java

Example09
JCode Cell
1 
2package com.durgasoft.validator;
3 
4import org.springframework.validation.Errors;
5import org.springframework.validation.ValidationUtils;
6import org.springframework.validation.Validator;
7 
8import com.durgasoft.command.User;
9 
10public class UserValidator implements Validator {
11 
12@Override
13public boolean supports(Class<?> cls) {
14 
15return User.class.isAssignableFrom(cls);
16}
17 
18@Override
19public void validate(Object command, Errors errors) {
20ValidationUtils.rejectIfEmpty(errors, "uname", "uname.required");
21ValidationUtils.rejectIfEmpty(errors, "upwd", "upwd.required");
22ValidationUtils.rejectIfEmpty(errors, "uage", "uage.required");
23ValidationUtils.rejectIfEmpty(errors, "uemail", "uemail.required");
24ValidationUtils.rejectIfEmpty(errors, "umobile", "umobile.required");
25 
26User user = (User)command;
27if(!user.getUpwd().equals("") && user.getUpwd().length() < 6) {
28 errors.rejectValue("upwd", "upwd.minLength");
29}
30if(!user.getUpwd().equals("") && user.getUpwd().length() > 10) {
31 errors.rejectValue("upwd", "upwd.maxLength");
32}
33if(user.getUage() < 18 || user.getUage() > 30) {
34 errors.rejectValue("uage", "uage.range");
35}
36if(!user.getUemail().equals("") && !user.getUemail().contains("@")) {
37 errors.rejectValue("uemail", "uemail.invalid");
38}
39if(!user.getUmobile().equals("") && !user.getUmobile().startsWith("91-")) {
40 errors.rejectValue("umobile", "umobile.invalid");
41}
42 
43}
44 
45}
46

Spring Data Validations By using Spring provided Error class — ds-servlet.xml

validation_Messages.properties

uname.required = User Name is Required. upwd.required = User Password is required. uage.required = User Age is Required. uemail.required = User Email Id Required. umobile.required = User Mobile Number is Required. upwd.minLength = User Password must be minimum 6 characters. upwd.maxLength = User Password must be maximum 10 characters. uage.range = User Age must be in the range from 18 to 30. uemail.invalid = User Email Id is Invalid. umobile.invalid = User Mobile Number is Invalid.

Example10
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:p="http://www.springframework.org/schema/p"
6xmlns:context="http://www.springframework.org/schema/context"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/context
11http://www.springframework.org/schema/context/spring-context.xsd">
12 
13<bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
14<property name="basename" value="com/durgasoft/resources/validation_Messages"/>
15</bean>
16<bean name="userValidator" class="com.durgasoft.validator.UserValidator"/>
17<bean name="/reg" class="com.durgasoft.controller.UserController">
18<property name="formView" value="registrationform"/>
19<property name="validator" ref="userValidator"/>
20<property name="commandName" value="user"/>
21<property name="commandClass" value="com.durgasoft.command.User"/>
22</bean>
23 
24<bean name="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
25 
26<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
27<property name="prefix" value="/WEB-INF/"/>
28<property name="suffix" value=".jsp"/>
29</bean>
30</beans>
31

Spring Data Validations By using Spring provided Error class — web.xml

Example11
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
4<display-name>app7</display-name>
5<welcome-file-list>
6<welcome-file>index.html</welcome-file>
7<welcome-file>index.htm</welcome-file>
8<welcome-file>index.jsp</welcome-file>
9<welcome-file>default.html</welcome-file>
10<welcome-file>default.htm</welcome-file>
11<welcome-file>default.jsp</welcome-file>
12</welcome-file-list>
13<servlet>
14<servlet-name>ds</servlet-name>
15<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
16<load-on-startup>1</load-on-startup>
17</servlet>
18<servlet-mapping>
19<servlet-name>ds</servlet-name>
20<url-pattern>/</url-pattern>
21</servlet-mapping>
22</web-app>
23

Java Provided Validation API

Validation-API is a specification provided JAVA and it is implemented by Third party vendors.

Hibernate has provided its validation API which contains Java provided Validation API and some extra validation rules.

  • @NotEmpty

 It will be applied to the bean variables or getter methods.  It will check whether data is existed in the respecxtive bean property or not.  If the data is not existed in the bean property then it will raise validation error.  It is applicable for only String type propertirs.

  • @NotNull

 It will be applied to the bean variables or getter methods.  It will check whether data/value is existed in the respective bean property or not.  If the data is not existed in the bean property then it will raise validation error.  It is applicable for only Numeric Data type propertirs.

  • @Size

 It will be applied to the bean variables or getter methods.  It will be applied for String type properties.  It will check whether the properties value is as per the specified minimum length

constraint and maximum length contraint or not.  It will take two properties min and max.

Note: If we dont want to use @Size annotation then we will use @Min and @Max annotation

  • @Range

 It will be applied to the bean variables or getter methods.  It is applied for the numeric data type properties.  It will check the value as per the specified range.  It will take two parameters min and max

  • @Pattern

 It will be applied either for property or for getter method directly.  It will check whether the property data is as per the provided reg exp.  It will take a parameter like "regexp", it will take pattern.

  • @Email

 It will be applied either for property or for getter method directly.  It will check whether the value of a property is email id or not.  It will not require any parameter.

  • @DateTimeFormat

 It will be applied either for property or for getter method directly.  It will be applied for Date type properties.  It will check whether the date value in a property is as per the specified format or not.  It will take a parameter like "pattern" to represent Date type patterns.  It will be applied for the properties in bean of Date type.

  • @Past

 It will be applied either for property or for getter method directly.  It will check whether the date is past date or not.  It will be applied for the properties in bean of Date type.

Steps

  • Use all the validation related annotations in Bean classes.
  • Declare properties file under src and provide validation messages.
  • Enable Annotations in Spring application through Spring configuration file.
  • Display Validation messages inside the pages.

There are two ways to define validation messages in Spring applications.

  • Provide validation messages directly in the Annotation.

public class User{ @NotEmpty(message="User Name is Required") private String uname @Size(min=6, max=10, message="User password must be minimum 6 characters and maximum 10 characters) prvate String upwd; }

  • Provide validation messages through properties file.

validation_Messages.properties

NotEmpty.user.uname = User Name is Required. Size.user.upwd = User Password must be minimum {2} characters and maximum {1} characters

To define validation messages in properties file then we have to use the following format. Annotation_Name.Model_name.Prop_Name = Validation Message

EX:

NotEmpty.user.uname=User Name is Required. NotEmpty.user.upwd=User Password is Required.

To enable Annotations in Spring applications we have to use the following tags in ds-servlet.xml

<context:component-scan base-package="com.durgasoft"/> <mvc:annotation-driven>

To declare controller class and to define request mapping for the COntroller class we have to use

the following annotations — index.jsp

@Controller @RequestMapping

To use the above annotations in Spring web applications we have to use the following JARs in web application lib folder.

1) All Spring web MVC JARs 2) clasmate-varsion.jar 3) hibernate-validator-5.x/4.x.final.jar 4) jboss-logging-version.jar 5) validation-api-version.jar

Example:

Example14
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5<html>
6<head>
7<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<jsp:forward page="reg"/>
12</body>
13</html>
14

the following annotations — registrationform.jsp

Example15
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
5<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
6<html>
7<head>
8<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
9<title>Insert title here</title>
10<style type="text/css">
11.error{
12color: red;
13font-family: consolas;
14font-style: italic;
15font-weight: bold;
16font-size: large;
17}
18</style>
19</head>
20<body>
21<br><br><br>
22<h2 style="color: red;" align="center">Durga Software Solutions</h2>
23<h3 style="color: red;" align="center">Student Registration Form</h3>
24<form:form method="POST" action="reg" commandName="user">
25<center>
26<table>
27<tr>
28<td>User Name</td>
29<td><form:input path="uname"/></td>
30<td><form:errors path="uname" cssClass="error"/>
31</tr>
32<tr>
33<td>User Password</td>
34<td><form:password path="upwd"/></td>
35<td><form:errors path="upwd" cssClass="error"/>
36</tr>
37<tr>
38<td>User Age</td>
39<td><form:input path="uage"/></td>
40<td><form:errors path="uage" cssClass="error"/>
41</tr>
42<tr>
43<td>User Date Of Birth</td>
44<td><form:input path="udob"/></td>
45<td><form:errors path="udob" cssClass="error"/>
46</tr>
47<tr>
48<td>User Email Id</td>
49<td><form:input path="uemail"/></td>
50<td><form:errors path="uemail" cssClass="error"/>
51</tr>
52<tr>
53<td>User Mobile No</td>
54<td><form:input path="umobile"/></td>
55<td><form:errors path="umobile" cssClass="error"/>
56</tr>
57<tr>
58<td><input type="submit" value="Registration"/></td>
59</tr>
60</table>
61</center>
62</form:form>
63</body>
64</html>
65

the following annotations — registrationdetails.jsp

Example16
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5<html>
6<head>
7<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<br><br><br>
12<h2 style="color: red;" align="center">Durga Software Solutions</h2>
13<h3 style="color: red;" align="center">User Registration Details</h3>
14<center>
15<table border="1">
16<tr>
17<td>User Name</td>
18<td>${user.uname}</td>
19</tr>
20<tr>
21<td>User Password</td>
22<td>${user.upwd}</td>
23</tr>
24 
25<tr>
26<td>User Age</td>
27<td>${user.uage}</td>
28</tr>
29<tr>
30<td>User Date Of Birth</td>
31<td>${user.udob}</td>
32</tr>
33<tr>
34<td>User Email Id</td>
35<td>${user.uemail}</td>
36</tr>
37<tr>
38<td>User Mobile No</td>
39<td>${user.umobile}</td>
40</tr>
41</table>
42</center>
43</body>
44</html>
45

the following annotations — User.java

Example17
JCode Cell
1 
2package com.durgasoft.command;
3 
4import java.util.Date;
5 
6 
7import javax.validation.constraints.NotNull;
8import javax.validation.constraints.Past;
9import javax.validation.constraints.Pattern;
10import javax.validation.constraints.Size;
11 
12import org.hibernate.validator.constraints.Email;
13import org.hibernate.validator.constraints.NotEmpty;
14import org.hibernate.validator.constraints.Range;
15import org.springframework.format.annotation.DateTimeFormat;
16 
17 
18public class User {
19@NotEmpty
20private String uname;
21 
22@NotEmpty
23@Size(max=10, min=6)
24private String upwd;
25 
26@NotNull
27@Range(min=18, max=20)
28private int uage;
29 
30@NotNull
31@DateTimeFormat(pattern="dd/MM/yyyy")
32@Past
33private Date udob;
34 
35@NotEmpty
36@Email
37private String uemail;
38 
39@NotEmpty
40@Pattern(regexp="91-[0-9]{10}")
41private String umobile;
42 
43public String getUname() {
44return uname;
45}
46public void setUname(String uname) {
47this.uname = uname;
48}
49public String getUpwd() {
50return upwd;
51}
52public void setUpwd(String upwd) {
53this.upwd = upwd;
54}
55public int getUage() {
56return uage;
57}
58public void setUage(int uage) {
59this.uage = uage;
60}
61public void setUdob(Date udob) {
62this.udob = udob;
63}
64public Date getUdob() {
65return udob;
66}
67public String getUemail() {
68return uemail;
69}
70public void setUemail(String uemail) {
71this.uemail = uemail;
72}
73public String getUmobile() {
74return umobile;
75}
76public void setUmobile(String umobile) {
77this.umobile = umobile;
78}
79 
80 
81}
82

the following annotations — UserController.java

Example18
JCode Cell
1 
2package com.durgasoft.controller;
3 
4 
5import javax.validation.Valid;
6 
7import org.springframework.stereotype.Controller;
8import org.springframework.ui.Model;
9import org.springframework.validation.BindingResult;
10import org.springframework.web.bind.annotation.RequestMapping;
11import org.springframework.web.bind.annotation.RequestMethod;
12import org.springframework.web.servlet.ModelAndView;
13import org.springframework.web.servlet.config.annotation.EnableWebMvc;
14 
15import com.durgasoft.command.User;
16 
17@Controller
18@RequestMapping("/reg")
19 
20public class UserController {
21@RequestMapping(method = RequestMethod.GET)
22public String showPage(Model model) {
23model.addAttribute("user", new User());
24return "registrationform";
25}
26 
27@RequestMapping(method = RequestMethod.POST)
28public ModelAndView registration(@Valid User user, BindingResult errors, Model model){
29model.addAttribute("user", user);
30if(errors.hasErrors()) {
31 return new ModelAndView("registrationform", "user", user);
32}else {
33 return new ModelAndView("registrationdetails", "user", user);
34}
35}
36}
37

the following annotations — ds-servlet.xml

validation_Messages.properties

typeMismatch = {0} is in invalid format NotEmpty.user.uname = User Name is Required. NotEmpty.user.upwd = User Password is Required. Size.user.upwd = User Password must be minimum {2} characters and maximum {1} characters. NotNull.user.uage = User Age is Required. Range.user.uage = User Age must be in the range from {2} through {1} Years. NotNull.user.udob = User Date Of Birth is Required. DateTimeFormat.user.udob = User Date Of Birth is Invalid. Past.user.udob = User Date of Birth Must be Past Date. NotEmpty.user.uemail = User Email Id is Required. Email.user.uemail = User Email Id is Invalid. NotEmpty.user.umobile = User Mobile No is Required. Pattern.user.umobile = User Mobile No must be in the pattern like "91-DDDDDDDDDD".

Example19
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns = "http://www.springframework.org/schema/beans"
4xmlns:context = "http://www.springframework.org/schema/context"
5xmlns:mvc = "http://www.springframework.org/schema/mvc"
6xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
7xsi:schemaLocation = "
8http://www.springframework.org/schema/beans
9http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
10http://www.springframework.org/schema/context
11http://www.springframework.org/schema/context/spring-context-3.0.xsd
12http://www.springframework.org/schema/mvc
13http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
14 
15<context:component-scan base-package="com.durgasoft"/>
16<mvc:annotation-driven/>
17 
18<bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
19<property name="basename" value="com/durgasoft/resources/validation_Messages"/>
20</bean>
21 
22<bean name="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
23 
24<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
25<property name="prefix" value="/WEB-INF/"/>
26<property name="suffix" value=".jsp"/>
27</bean>
28</beans>
29

the following annotations — web.xml

Example20
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
4<display-name>app7</display-name>
5<welcome-file-list>
6<welcome-file>index.html</welcome-file>
7<welcome-file>index.htm</welcome-file>
8<welcome-file>index.jsp</welcome-file>
9<welcome-file>default.html</welcome-file>
10<welcome-file>default.htm</welcome-file>
11<welcome-file>default.jsp</welcome-file>
12</welcome-file-list>
13<servlet>
14<servlet-name>ds</servlet-name>
15<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
16<load-on-startup>1</load-on-startup>
17</servlet>
18<servlet-mapping>
19<servlet-name>ds</servlet-name>
20<url-pattern>/</url-pattern>
21</servlet-mapping>
22</web-app>
23

Extra jars required along with Spring jars

classmate-0.8.0.jar hibernate-validator-5.0.1.final.jar jboss-logging-3.1.0.ga.jar validation-api-1.1.0.final.jar

Example on Data Validations through Java Validation API provided Annotations by using

properties file provided validation Messages — index.jsp

Example22
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5<html>
6<head>
7<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<jsp:forward page="reg"/>
12</body>
13</html>
14

properties file provided validation Messages — reg_form.jsp

Example23
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
5<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
6<html>
7<head>
8<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
9<title>Insert title here</title>
10<style type="text/css">
11.error{
12color: red;
13font-family: consolas;
14font-style: italic;
15font-weight: bold;
16font-size: large;
17}
18</style>
19</head>
20<body>
21<h2 style="color: red;" align="center">Durga Software Solutions</h2>
22<h3 style="color: blue;" align="center">User Registration Form</h3>
23<form:form method="POST" action="reg" commandName="user">
24<center>
25<table>
26<tr>
27<td>User Name</td>
28<td><form:input path="uname"/></td>
29<td><form:errors path="uname" cssClass="error"/></td>
30</tr>
31<tr>
32<td>User Password</td>
33<td><form:password path="upwd"/></td>
34<td><form:errors path="upwd" cssClass="error"/></td>
35</tr>
36<tr>
37<td>User Age</td>
38<td><form:input path="uage"/></td>
39<td><form:errors path="uage" cssClass="error"/></td>
40</tr>
41<tr>
42<td>User Date Of Birth</td>
43<td><form:input path="udob"/></td>
44<td><form:errors path="udob" cssClass="error"/></td>
45</tr>
46<tr>
47<td>User Email Id</td>
48<td><form:input path="uemail"/></td>
49<td><form:errors path="uemail" cssClass="error"/></td>
50</tr>
51<tr>
52<td>User Mobile No</td>
53<td><form:input path="umobile"/></td>
54<td><form:errors path="umobile" cssClass="error"/></td>
55</tr>
56<tr>
57<td><input type="submit" value="Registration"/></td>
58</tr>
59</table>
60</center>
61</form:form>
62</body>
63</html>
64

properties file provided validation Messages — registrationdetails.jsp

Example24
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5<html>
6<head>
7<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h2 style="color: red;" align="center">Durga Software Solutions</h2>
12<h3 style="color: blue;" align="center">User Registration Form</h3>
13<center>
14<table border="1">
15<tr>
16<td>User Name</td>
17<td>${user.uname}</td>
18</tr>
19<tr>
20<td>User Password</td>
21<td>${user.upwd}</td>
22</tr>
23<tr>
24<td>User Age</td>
25<td>${user.uage}</td>
26</tr>
27<tr>
28<td>User Date Of Birth</td>
29<td>${user.udob}</td>
30</tr>
31<tr>
32<td>User Email Id</td>
33<td>${user.uemail}</td>
34</tr>
35<tr>
36<td>User Mobile No</td>
37<td>${user.umobile}</td>
38</tr>
39</table>
40</center>
41</body>
42</html>
43

properties file provided validation Messages — User.java

Example25
JCode Cell
1 
2package com.durgasoft.command;
3 
4import java.util.Date;
5 
6import javax.validation.constraints.NotNull;
7import javax.validation.constraints.Past;
8import javax.validation.constraints.Pattern;
9import javax.validation.constraints.Size;
10 
11import org.hibernate.validator.constraints.Email;
12import org.hibernate.validator.constraints.NotEmpty;
13import org.hibernate.validator.constraints.Range;
14import org.springframework.format.annotation.DateTimeFormat;
15 
16public class User {
17@NotEmpty(message="User Name is required")
18private String uname;
19 
20@NotEmpty(message="User Password is Required")
21@Size(min=6, max=10, message="User Password must be minimum 6 and maximum 10 characters")
22private String upwd;
23 
24@NotNull(message="User is Required")
25@Range(min=18, max=25, message="User Age must be minimum 18 and maximum 25")
26private int uage;
27 
28@NotNull(message="User Date of Birth is Required")
29@DateTimeFormat(pattern="dd/MM/yyyy")
30@Past(message="User DOB must be past date")
31private Date udob;
32 
33@NotEmpty(message="User Email Id is Required")
34@Email
35private String uemail;
36 
37@NotEmpty(message="User Mobile No is Required")
38@Pattern(regexp="91-[0-9]{10}", message="User Mobile Number must be in 91-DDDDDDDDDD format")
39private String umobile;
40 
41public String getUname() {
42return uname;
43}
44public void setUname(String uname) {
45this.uname = uname;
46}
47public String getUpwd() {
48return upwd;
49}
50public void setUpwd(String upwd) {
51this.upwd = upwd;
52}
53public int getUage() {
54return uage;
55}
56public void setUage(int uage) {
57this.uage = uage;
58}
59public Date getUdob() {
60return udob;
61}
62public void setUdob(Date udob) {
63this.udob = udob;
64}
65public String getUemail() {
66return uemail;
67}
68public void setUemail(String uemail) {
69this.uemail = uemail;
70}
71public String getUmobile() {
72return umobile;
73}
74public void setUmobile(String umobile) {
75this.umobile = umobile;
76}
77 
78 
79}
80

properties file provided validation Messages — UserController.java

Example26
JCode Cell
1 
2package com.durgasoft.controller;
3 
4import javax.validation.Valid;
5 
6import org.springframework.stereotype.Controller;
7import org.springframework.ui.Model;
8import org.springframework.validation.BindingResult;
9import org.springframework.web.bind.annotation.RequestMapping;
10import org.springframework.web.bind.annotation.RequestMethod;
11import org.springframework.web.servlet.ModelAndView;
12 
13import com.durgasoft.command.User;
14 
15@Controller
16@RequestMapping("/reg")
17public class UserController {
18@RequestMapping(method = RequestMethod.GET)
19public String showForm(Model model) {
20model.addAttribute("user", new User());
21return "reg_form";
22}
23 
24@RequestMapping(method = RequestMethod.POST)
25public ModelAndView registration(@Valid User user, BindingResult errors, Model model){
26if(errors.hasErrors()) {
27 return new ModelAndView("reg_form", "user", user);
28}else {
29 return new ModelAndView("registrationdetails", "user", user);
30}
31}
32}
33

properties file provided validation Messages — ds-servlet.xml

error_Messages.properties

typeMismatch = {0} is in invalid format

Example27
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns = "http://www.springframework.org/schema/beans"
4xmlns:context = "http://www.springframework.org/schema/context"
5xmlns:mvc = "http://www.springframework.org/schema/mvc"
6xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
7xsi:schemaLocation = "
8http://www.springframework.org/schema/beans
9http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
10http://www.springframework.org/schema/context
11http://www.springframework.org/schema/context/spring-context-3.0.xsd
12http://www.springframework.org/schema/mvc
13http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
14<context:component-scan base-package="com.durgasoft"/>
15<mvc:annotation-driven/>
16<bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
17<property name="basename" value="com/durgasoft/resources/error_Messages"/>
18</bean>
19<bean name="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
20 
21<bean name="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
22<property name="prefix" value="/WEB-INF/"/>
23<property name="suffix" value=".jsp"/>
24</bean>
25</beans>
26

properties file provided validation Messages — web.xml

Example28
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
4<display-name>app14</display-name>
5<welcome-file-list>
6<welcome-file>index.html</welcome-file>
7<welcome-file>index.htm</welcome-file>
8<welcome-file>index.jsp</welcome-file>
9<welcome-file>default.html</welcome-file>
10<welcome-file>default.htm</welcome-file>
11<welcome-file>default.jsp</welcome-file>
12</welcome-file-list>
13<servlet>
14<servlet-name>ds</servlet-name>
15<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
16<load-on-startup>1</load-on-startup>
17</servlet>
18<servlet-mapping>
19<servlet-name>ds</servlet-name>
20<url-pattern>/</url-pattern>
21</servlet-mapping>
22</web-app>
23
📝 Key Takeaways
  • Client-side validation is a convenience; server-side validation is the one that protects you
  • Errors carries the rejection back to the same form so the user does not retype everything
  • Annotation-driven validation needs its own jars alongside the Spring ones
  • Messages in a properties file can be changed without touching Java code