Recent Posts

Saturday, 21 September 2019

Spring 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.
1. Client Side Data Validations
2. Server Side Data Validations

1. 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.

2. 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.
1. By Using Spring provided Error class.
2. By Using Java provided validation annotations

1. Spring Data Validations By using Spring provided Error class
     To provide data validations in this approach we have to use the following approach.
1. 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
c) public void rejectValue(String var_Name, String error_Code)
d) Where variable name is a variable in Comand class.
e) Where error_Code is either validation message directly or a key from the propertirs file which had validation message.
2. Provide Properties file under src or in a package under properties file with validation messages in the form of key-value pairs.
3. Configure Validator class and Properties file with "messageSource" property under org.springframework.context.support.ResourceBundleMessageSource
4. Display Validation messages in User forms by using <form:errors/> tag.
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
   <jsp:forward page="reg"/>
</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 type="text/css">
.error {
   color: red;
   font-family: consolas;
   font-style: italic;
   font-weight: bold;
   font-size: large;
   font-style: italic;
   font-weight: bold;
}
</style>
</head>
<body>
   <br>
   <h3 style="color: red;" align="center">Student Registration Form</h3>
   <form:form method="POST" action="reg" commandName="user">
      <center>
         <table>
            <tr>
               <td>User Name</td>
               <td><form:input path="uname" /></td>
               <td><form:errors path="uname" cssClass="error" />
            </tr>
            <tr>
               <td>User Age</td>
               <td><form:input path="uage" /></td>
               <td><form:errors path="uage" cssClass="error" />
            </tr>
            <tr>
               <td>User Email Id</td>
               <td><form:input path="uemail" /></td>
               <td><form:errors path="uemail" cssClass="error" />
            </tr>
            <tr>
               <td>User Mobile No</td>
               <td><form:input path="umobile" /></td>
               <td><form:errors path="umobile" cssClass="error" />
            </tr>
            <tr>
               <td><input type="submit" value="Registration" /></td>
            </tr>
         </table>
      </center>
   </form:form>
</body>
</html>
registrationDetails.jsp
<%@ 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>
   <br>
   <br>
   <h3 style="color: red;" align="center">User Registration Details</h3>
   <center>
      <table border="1">
         <tr>
            <td>User Name</td>
            <td>${user.uname}</td>
         </tr>
         <tr>
            <td>User Password</td>
            <td>${user.upwd}</td>
         </tr>
         <tr>
            <td>User Age</td>
            <td>${user.uage}</td>
         </tr>
         <tr>
            <td>User Email Id</td>
            <td>${user.uemail}</td>
         </tr>
         <tr>
            <td>User Mobile No</td>
            <td>${user.umobile}</td>
         </tr>
      </table>
   </center>
</body>
</html>
User.java
package com.ashok.spring.mvc.command;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class User {
   private String uname;
   private String upwd;
   private int uage;
   private String uemail;
   private String umobile;

   public String getUname() {
      return uname;
   }

   public void setUname(String uname) {
      this.uname = uname;
   }

   public String getUpwd() {
      return upwd;
   }

   public void setUpwd(String upwd) {
      this.upwd = upwd;
   }

   public int getUage() {
      return uage;
   }

   public void setUage(int uage) {
      this.uage = uage;
   }

   public String getUemail() {
      return uemail;
   }

   public void setUemail(String uemail) {
      this.uemail = uemail;
   }

   public String getUmobile() {
      return umobile;
   }

   public void setUmobile(String umobile) {
      this.umobile = umobile;
   }
}
UserController.java
package com.ashok.spring.mvc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.ashok.spring.mvc.command.User;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class UserController extends SimpleFormController {
   @Override
   protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
         BindException errors) throws Exception {
      User user = (User) command;
      return new ModelAndView("registrationdetails", "user", user);
   }
}
UserValidator.java
package com.ashok.spring.mvc.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.ashok.spring.mvc.command.User;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class UserValidator implements Validator {
   @Override
   public boolean supports(Class clazz) {
      return User.class.isAssignableFrom(clazz);
   }

   @Override
   public void validate(Object target, Errors errors) {
      ValidationUtils.rejectIfEmpty(errors, "uname", "uname.required");
      ValidationUtils.rejectIfEmpty(errors, "upwd", "upwd.required");
      ValidationUtils.rejectIfEmpty(errors, "uage", "uage.required");
      ValidationUtils.rejectIfEmpty(errors, "uemail", "uemail.required");
      ValidationUtils.rejectIfEmpty(errors, "umobile", "umobile.required");
      User user = (User) target;
      if (!user.getUpwd().equals("") && user.getUpwd().length() < 6) {
         errors.rejectValue("upwd", "upwd.minLength");
      }
      if (!user.getUpwd().equals("") && user.getUpwd().length() > 10) {
         errors.rejectValue("upwd", "upwd.maxLength");
      }
      if (user.getUage() < 18 || user.getUage() > 30) {
         errors.rejectValue("uage", "uage.range");
      }
      if (!user.getUemail().equals("") && !user.getUemail().contains("@")) {
         errors.rejectValue("uemail", "uemail.invalid");
      }
      if (!user.getUmobile().equals("") && !user.getUmobile().startsWith("91-")) {
         errors.rejectValue("umobile", "umobile.invalid");
      }
   }
}
validationMessages.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
uemail.invalid = User Email Id is Invalid.
umobile.invalid = User Mobile Number is Invalid.
ds-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

   <bean name="messageSource"
      class="org.springframework.context.support.ResourceBundleMessageSource">
      <property name="basename"
         value="com/ashok/spring/mvc/validationMessages" />
   </bean>
   <bean name="userValidator"
      class="com.ashok.spring.mvc.validator.UserValidator" />
   <bean name="/reg"
      class="com.ashok.spring.mvc.controller.UserController">
      <property name="formView" value="registrationform" />
      <property name="validator" ref="userValidator" />
      <property name="commandName" value="user" />
      <property name="commandClass"
         value="com.ashok.spring.mvc.command.User" />
   </bean>
   <bean name="handlerMapping"
      class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
   <bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
   <display-name>MVC</display-name>
   <welcome-file-list>
      <welcome-file>index.html</welcome-file>
      <welcome-file>index.htm</welcome-file>
      <welcome-file>index.jsp</welcome-file>
      <welcome-file>default.html</welcome-file>
      <welcome-file>default.htm</welcome-file>
      <welcome-file>default.jsp</welcome-file>
   </welcome-file-list>
   <servlet>
      <servlet-name>ds</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>ds</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>
2. 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.
1. @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.

2. @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.

3.@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

4. @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

5. @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.

6. @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.

7. @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.

8. @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
1. Use all the validation related annotations in Bean classes.
2. Declare properties file under src and provide validation messages.
3. Enable Annotations in Spring application through Spring configuration file.
4. Display Validation messages inside the pages.

     There are two ways to define validation messages in Spring applications.
1. 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;
}
2. Provide validation messages through properties file.
validationMessages.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
E.g.
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.ashok.spring"/>
<mvc:annotation-driven>

     To declare controller class and to define request mapping for the Controller class we have to use the following annotations:
@Controller
@RequestMapping
E.g
index.jsp 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
   <jsp:forward page="reg" />
</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 type="text/css">
.error {
   color: red;
   font-family: consolas;
   font-style: italic;
   font-weight: bold;
   font-size: large;
   font-style: italic;
   font-weight: bold;
}
</style>
</head>
<body>
   <br>
   <h3 style="color: red;" align="center">Student Registration Form</h3>
   <form:form method="POST" action="reg" commandName="user">
      <center>
         <table>
            <tr>
               <td>User Name</td>
               <td><form:input path="uname" /></td>
               <td><form:errors path="uname" cssClass="error" />
            </tr>
            <tr>
               <td>User Age</td>
               <td><form:input path="uage" /></td>
               <td><form:errors path="uage" cssClass="error" />
            </tr>
            <tr>
               <td>User Email Id</td>
               <td><form:input path="uemail" /></td>
               <td><form:errors path="uemail" cssClass="error" />
            </tr>
            <tr>
               <td>User Mobile No</td>
               <td><form:input path="umobile" /></td>
               <td><form:errors path="umobile" cssClass="error" />
            </tr>
            <tr>
               <td><input type="submit" value="Registration" /></td>
            </tr>
         </table>
      </center>
   </form:form>
</body>
</html>
registrationDetails.jsp
<%@ 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>
   <br>
   <br>
   <h3 style="color: red;" align="center">User Registration Details</h3>
   <center>
      <table border="1">
         <tr>
            <td>User Name</td>
            <td>${user.uname}</td>
         </tr>
         <tr>
            <td>User Password</td>
            <td>${user.upwd}</td>
         </tr>
         <tr>
            <td>User Age</td>
            <td>${user.uage}</td>
         </tr>
         <tr>
            <td>User Email Id</td>
            <td>${user.uemail}</td>
         </tr>
         <tr>
            <td>User Mobile No</td>
            <td>${user.umobile}</td>
         </tr>
      </table>
   </center>
</body>
</html>
package com.ashok.spring.mvc.command;

import java.util.Date;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.DateTimeFormat;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class User {
   @NotEmpty
   private String uname;
   @NotEmpty 
   @Size(max=10, min=6)
   private String upwd;
   @NotNull
   @Range(min=18, max=20)
   private int uage;
   @NotNull 
   @DateTimeFormat(pattern="dd/MM/yyyy") 
   @Past
   private Date udob;
   @NotEmpty 
   @Email
   private String uemail;
   @NotEmpty 
   @Pattern(regexp="91-[0-9]{10}")
   private String umobile;

   public String getUname() {
      return uname;
   }

   public void setUname(String uname) {
      this.uname = uname;
   }

   public String getUpwd() {
      return upwd;
   }

   public void setUpwd(String upwd) {
      this.upwd = upwd;
   }

   public int getUage() {
      return uage;
   }

   public void setUage(int uage) {
      this.uage = uage;
   }
   
   public Date getUdob() {
      return udob;
   }

   public void setUdob(Date udob) {
      this.udob = udob;
   }

   public String getUemail() {
      return uemail;
   }

   public void setUemail(String uemail) {
      this.uemail = uemail;
   }

   public String getUmobile() {
      return umobile;
   }

   public void setUmobile(String umobile) {
      this.umobile = umobile;
   }
}
package com.ashok.spring.mvc.controller;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.ashok.spring.mvc.command.User;

/**
 * 
 * @author ashok.mariyala
 *
 */
@Controller
@RequestMapping("/reg")
public class UserController {
   @RequestMapping(method = RequestMethod.GET)
   public String showPage(Model model) {
      model.addAttribute("user", new User());
      return "registrationform";
   }

   @RequestMapping(method = RequestMethod.POST)
   public ModelAndView registration(@Valid User user, BindingResult errors, Model model) {
      model.addAttribute("user", user);
      if (errors.hasErrors()) {
         return new ModelAndView("registrationform", "user", user);
      } else {
         return new ModelAndView("registrationdetails", "user", user);
      }
   }
}
validationMessages.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".
ds-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.ashok.spring.mvc" />
   <mvc:annotation-driven />
   <bean name="messageSource"
      class="org.springframework.context.support.ResourceBundleMessageSource">
      <property name="basename"
         value="com/ashok/spring/mvc/validationMessages" />
   </bean>
   <bean name="handlerMapping"
      class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
   <bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
   <display-name>MVC</display-name>
   <welcome-file-list>
      <welcome-file>index.html</welcome-file>
      <welcome-file>index.htm</welcome-file>
      <welcome-file>index.jsp</welcome-file>
      <welcome-file>default.html</welcome-file>
      <welcome-file>default.htm</welcome-file>
      <welcome-file>default.jsp</welcome-file>
   </welcome-file-list>
   <servlet>
      <servlet-name>ds</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>ds</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>


No comments:

Post a Comment