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
Loading editor…

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

Example05
Loading editor…

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

Example06
Loading editor…

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

Example07
Loading editor…

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

Example08
Loading editor…

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

Example09
Loading editor…

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
Loading editor…

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

Example11
Loading editor…

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
Loading editor…

the following annotations — registrationform.jsp

Example15
Loading editor…

the following annotations — registrationdetails.jsp

Example16
Loading editor…

the following annotations — User.java

Example17
Loading editor…

the following annotations — UserController.java

Example18
Loading editor…

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
Loading editor…

the following annotations — web.xml

Example20
Loading editor…

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
Loading editor…

properties file provided validation Messages — reg_form.jsp

Example23
Loading editor…

properties file provided validation Messages — registrationdetails.jsp

Example24
Loading editor…

properties file provided validation Messages — User.java

Example25
Loading editor…

properties file provided validation Messages — UserController.java

Example26
Loading editor…

properties file provided validation Messages — ds-servlet.xml

error_Messages.properties

typeMismatch = {0} is in invalid format

Example27
Loading editor…

properties file provided validation Messages — web.xml

Example28
Loading editor…
📝 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

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.