Nearby lessons

11 of 35

Spring - Validation

📌 What You Will Learn
  • Understand Spring - Validation
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Spring - Validation step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

3)Configure Validator class in spring configuration file

In spring configuration file, we have to configure Validator class as a bean with

Resource property.

3)Configure Validator class in spring configuration file

object[Errors] by using getAllErrors() method.

Example:

Employee.java

package com.durgasoft.beans;

public class Employee {

private String eid;

private String ename;

private float esal;

private int eage;

private String eemail;

private String emobile;

setXXX() and 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.durgasoft.validations;

import com.durgasoft.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("@durgasoft.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.durgasoft.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.durgasoft.validations.EmployeeValidator">

<property name="resource"

value="/com/durgasoft/resources/messages.properties"/>

</bean>

</beans>

Test.java0

package com.durgasoft.test;

import com.durgasoft.beans.Employee;

import com.durgasoft.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.durgasoft.beans.Employee");

empValidator.validate(emp, results);

List<ObjectError> list = results.getAllErrors();

for(ObjectError e: list){

System.out.println(e.getDefaultMessage());

}

}

}

Event Handling

In general, in GUI Applications, when we click on a button, when select an item in check

boxes, radio buttons, List boxes, choice boxes ... automatically an event will be rised,

where the generated event will not be handled by the respective GUI components,

where the generated events are handled by some component internally called as

"Listeners"[Handlers]

In Event Handling, the main intention of Listeners is to listen the events rised by the

GUI Components, handle that events and generating results back to the GUI

Applications.

Similarily, in spring applications, IOC Container is able to rise events when it was

started, refreshed, stopped and closed. In this context, to handle the generated events

Spring Framework has provided "Event Handling".

In Spring Framework, Event Handling capability is available with Application Context

only, not with BeanFactory. In Spring Framework Event Handling all events are

represented in the form of predefined classes in

"org.springframework.context.event" package like below.

1.ContextRefreshedEvent

2.ContextStartedEvent

3.ContextStoppedEvent

4.ContextClosedEvent

5.RequestHandledEvent

Where ContextRefreshedEvent will be rised when we start ApplicationContext or when

we access "refresh()" method on ApplicationContext.

Where ContextStartedEvent will be rised when we access "start()" method on

ApplicationContext.

Where ContextStoppedEvent will be rised when we access "stop()" method on

ApplicationContext.

Where ContextClosedEvent will be rised when we access "close()" method on

ApplicationContext.

Where RequestHandledEvent will be rised in web applications when request is handled

in Spring web applications.

To Handle all the above Events, Spring Framework has provided a Listener in the form

of "org.springframework.context.ApplicationListener" interface and it is having the

following to execute when the respective event is rised.

public void onApplicationEvent(XXXEvent e)

Note: ApplicationListener is able to listen all the events bydefault, if we want to filter

the events then we have to provide the respective Event type as Generic parameter.

EX: ApplicationListener<ContextStartedEvent> is able to listen only

ContextStartedEvent .

In Spring applications, if we want to implement event handling then we have to use the

following steps.

1.Create implementation classes for ApplicationListener interface and provide

implementation for onApplicationEvent(--) method.

2.Configure all implementation classes as bean components in spring configuration

file.

Note: To perform Event Handling in spring applications we have to use

"org.springframework.context.ConfigurableApplicationContext" container , it is a chaild

interface to ApplicationContext interface.

Example:

ContextRefreshedListenerImpl.java

package com.durgasoft.listeners;

import org.springframework.context.ApplicationListener;

import org.springframework.context.event.ContextRefreshedEvent;

public class ContextRefreshedListenerImpl implements

ApplicationListener<ContextRefreshedEvent>{

@Override

public void onApplicationEvent(ContextRefreshedEvent e) {

System.out.println("Application Context is Refreshed");

}

}

ContextStartedListenerImpl.java

package com.durgasoft.listeners;

import org.springframework.context.ApplicationListener;

import org.springframework.context.event.ContextStartedEvent;

public class ContextStartedListenerImpl implements

ApplicationListener<ContextStartedEvent>{

@Override

public void onApplicationEvent(ContextStartedEvent e) {

System.out.println("Application Context Started....");

}

}

ContextStoppedListenerImpl.java

package com.durgasoft.listeners;

import org.springframework.context.ApplicationListener;

import org.springframework.context.event.ContextStoppedEvent;

public class ContextStoppedListenerImpl implements

ApplicationListener<ContextStoppedEvent>{

@Override

public void onApplicationEvent(ContextStoppedEvent e) {

System.out.println("Application Context Stopped");

}

}

ContextClosedListenerImpl.java

package com.durgasoft.listeners;

import org.springframework.context.ApplicationListener;

import org.springframework.context.event.ContextClosedEvent;

public class ContextClosedListenerImpl implements

ApplicationListener<ContextClosedEvent>{

@Override

public void onApplicationEvent(ContextClosedEvent e) {

System.out.println("Application Context has Closed");

}

}

HelloBean.java

package com.durgasoft.beans;

public class HelloBean {

private String uname;

public String getUname() {

return uname;

}

public void setUname(String uname) {

this.uname = uname;

}

public String wish(){

return "Hello "+uname+"!";

}

}

applicationContext.xml

<beans>

<bean id="helloBean" class="com.durgasoft.beans.HelloBean">

<property name="uname" value="Durga"/>

</bean>

<bean id="contextRefreshedEvent"

class="com.durgasoft.listeners.ContextRefreshedListenerImpl"/>

<bean id="contextStartedEvent"

class="com.durgasoft.listeners.ContextStartedListenerImpl"/>

<bean id="contextStoppedEvent"

class="com.durgasoft.listeners.ContextStoppedListenerImpl"/>

<bean id="contextClosedEvent"

class="com.durgasoft.listeners.ContextClosedListenerImpl"/>

</beans>

Test.java

package com.durgasoft.test;

import com.durgasoft.beans.HelloBean;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ConfigurableApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

public static void main(String[] args)throws Exception {

ConfigurableApplicationContext context=new

ClassPathXmlApplicationContext("applicationContext.xml");

HelloBean hello=(HelloBean)context.getBean("helloBean");

System.out.println(hello.wish());

context.start();

context.refresh();

context.stop();

context.close();

}

}

Example02
JCode Cell
1 
2In test application get all validation messages from MapBindingResults
3
📝 Key Takeaways
  • Key ideas of Spring - Validation explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end