Friday, October 28, 2022

Spring - Bean Validations

  • The process of checking data validity before using data in applications is called as Data Validations.

  • In Web Applications, there are two types of data validations. 

    1. Client Side Data Validations
    2. Server Side Data Validations

1.Client-Side Data Validations: 

  • The process of checking whether data is valid or not at client browser before submitting request to the Server is called as Client Side Data Data Validations. To perform client side data validations we will use "Java Script" Functions.

2. Server Side Data Validations: 

  • The process of checking whether data is valid or not at server after getting request from client and before using data in application logic is called as Server side data validations. To perform Server side data validations we have to use Java code explicitly.

Note: 

  • If we use web Frameworks like Struts, JSF , SPring WEB MVC module then all these frameworks are able to provide their own validations services implicitly to perform data validations.
  • In Spring Core Module, to perform validations over the data after storing data in Bean objects Spring Framework has provided a predefined interface in the form of "org.springframework.validation.Validator" .

To perform bean validations in Spring applications ,we have to use the following steps.

1. Prepare a properties file with all validation messages:

  • Declare validation messages in the form of key-value pairs, where keys must be validation message code and value must be validation message.

  • Example: 
    • abc.properties
    • error.uname= User Name is required. error.password=User Password is required.

2.Prepare Validator class:

  • The main intention of the Validator class is to define all data validation logic w.r.t the bean properties.

Steps:

  1. Declare a user defined class.
  2. Implement org.springframework.validation.Validator interface. 
  3. Implement the Validator interface provided methods.
  4. Declare Resource property and its setXXX() method in order to represent the name and location of the properties file where all the validation messages exist.

3)Configure Validator class in spring configuration file:

  • In the spring configuration file, we have to configure Validator class as a bean with Resource property.

4)In test application get all validation messages from MapBindingResults object[Errors] by using getAllErrors() method.

Example:

Employee.java

package com.cloud.beans; 
public class Employee {
	private String eid; 
	private String ename; 
	private float esal; 
	private int eage; 
	private String eemail; 
	private String emobile;

	setXXX()  
	getXXX()

	public void getEmpDetails(){ 
		System.out.println("Employee Details"); 
		System.out.println("-----------------------"); 
		System.out.println("Employee Id :"+eid); 
		System.out.println("Employee Name :"+ename); 
		System.out.println("Employee Salary :"+esal); 
		System.out.println("Employee Email :"+eemail); 
		System.out.println("Employee Mobile :"+emobile);

	}
 }

messages.properties

error.eid.empty=Employee Id is required. 
error.eid.invalid=Invalid Employee Id.
error.ename.empty=Employee Name is required. 
error.esal.invalid=Employee Salary is Invalid.
error.eage.minage=Employee Age must not be less than 18 years. 
error.eage.maxage=Employee Age must not be greater than 30 years.
error.eemail.empty=Employee Email Id is required.
error.eemail.invalid=Employee Email Id is Invalid.
error.emobile.empty=Employee Mobile is required. 
error.emobile.invalid=Employee Mobile is Invalid.

EmployeeValidator.java

package com.cloud.validations;
import com.cloud.beans.Employee;
import java.util.Properties;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class EmployeeValidator implements Validator{ private Resource resource;

	public void setResource(Resource resource){ 
		this.resource=resource;
	}

	@Override
	public boolean supports(Class type) { 
		System.out.println("Hello");
		return Employee.class.equals(type); 
	}

	@Override
	public void validate(Object obj, Errors errors) {
	 try {
		System.out.println("Hello...validate()");
		Properties prop = PropertiesLoaderUtils.loadProperties(resource);
		
		Employee emp=(Employee)obj;
		
		if(emp.getEid() == null || emp.getEid() == ""){
			errors.rejectValue("eid", "error.eid.empty", prop.getProperty("error.eid.empty")); 
		} else{
			if(!emp.getEid().startsWith("DSS-")){
				errors.rejectValue("eid", "error.eid.invalid", prop.getProperty("error.eid.invalid"));
			}
		}

		if(emp.getEname() == null || emp.getEname() == ""){
			errors.rejectValue("ename", "error.ename.empty", prop.getProperty("error.ename.empty"));
		}

		if(emp.getEsal() <= 0.0f ){
			errors.rejectValue("esal","error.esal.invalid", prop.getProperty("error.esal.invalid")); 
		} 

		if(emp.getEage() < 18 ){
			errors.rejectValue("eage", "error.eage.minage", prop.getProperty("error.eage.minage")); }
		else if(emp.getEage() > 30 ){
			errors.rejectValue("eage", "error.eage.maxage", prop.getProperty("error.eage.maxage"));

		}

		if(emp.getEemail() == null || emp.getEemail() == ""){ 	
			errors.rejectValue("eemail","error.eemail.empty",prop.getProperty("error.eemail.empt y"));			
		}else{
			if(!emp.getEemail().endsWith("@cloud.com")){
				errors.rejectValue("eemail", "error.eemail.invalid", prop.getProperty("error.eemail.invalid"));
			}
		}

		if(emp.getEmobile() == null || emp.getEmobile() == ""){
			errors.rejectValue("emobile", "error.emobile.empty", prop.getProperty("error.emobile.empty"));
		}else{
			if(!emp.getEmobile().startsWith("91-")){
				errors.rejectValue("emobile", "error.emobile.invalid", prop.getProperty("error.emobile.invalid"));
			}
		}
	} catch (Exception e) { 
		e.printStackTrace();	
       }
    }
}

applicationContext.xml

<beans>
	<bean id="emp" class="com.cloudtechtwitter.beans.Employee">
		<property name="eid" value=""/>
		<property name="ename" value=""/> 
		<property name="esal" value=""/> 
		<property name="eage" value=""/> 
		<property name="eemail" value=""/> 
		<property name="emobile" value=""/>
	</bean>
	<bean id="empValidator" class="com.cloudtechtwitter.validations.EmployeeValidator">
		<property name="resource" value="/com/cloudtechtwitter/resources/messages.properties"/>
	</bean> 
</beans>

Test.java

package com.cloud.test;
import com.cloud.beans.Employee;
import com.cloud.validations.EmployeeValidator; 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; 
import org.springframework.validation.MapBindingResult;
import org.springframework.validation.ObjectError;

public class Test {
	public static void main(String[] args)throws Exception { 
		ApplicationContext context=
			new ClassPathXmlApplicationContext("applicationContext.xml"); 

		Employee emp=(Employee)context.getBean("emp"); 
		emp.getEmpDetails();

		EmployeeValidator empValidator = (EmployeeValidator)context.getBean("empValidator"); 

		Map<String, String> map = new HashMap<String, String>(); 
		MapBindingResult results = new MapBindingResult(map, "com.cloud.beans.Employee"); 
		empValidator.validate(emp, results);

		List<ObjectError> list = results.getAllErrors(); 
		for(ObjectError e: list){ 
			System.out.println(e.getDefaultMessage());
		}
	}
}

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS