Struts Validation Framework Tutorial with example.

Apache Struts has changed the way we develop a Web application. Since its inception as an MVC architecture, Struts has been extensively used in J2EE world to develop robust, extendable and effective web applications.

Introduction to Struts Validation Framework

[ad name=”AD_INBETWEEN_POST”] One of the important features of Struts framework is Struts Validation framework that performs validation on incoming form data. Validation framework was introduced by David Winterfeldt as an external plugin to Struts framework. It’s functionality has since been split so that validator can serve as the basis for a independant component and is now part of Jakarta Commons. The Struts framework’s simple validation interface alleviates much of the headache associated with handling data validation, allowing you to focus on validation code and not on the mechanics of capturing data and redisplaying incomplete or invalid data. In order to do form validation without Validator framework, one has to use validate() method of the form bean (ActionForm class) to perform this task. Also one has to handle error messages during manual validation. Lot of fields that we validate require same logic to validate them, hence code is unneccessarily duplicated (if not managed properly). Validation framework comes with set of useful routines to handle form validation automatically and it can handle both server side as well as client side form validation. If certain validation is not present, you can create your own validation logic and plug it into validation framework as a re-usable component. Validator uses two XML configuration files to determine which validation routines should be installed and how they should be applied for a given application, respectively. The first configuration file, validator-rules.xml, declares the validation routines that should be plugged into the framework and provides logical names for each of the validations. The validator-rules.xml file also defines client-side JavaScript code for each validation routine. Validator can be configured to send this JavaScript code to the browser so that validations are performed on the client side as well as on the server side. The second configuration file, validation.xml, defines which validation routines should be applied to which Form Beans. The definitions in this file use the logical names of Form Beans from the struts-config.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together. Using the Validator framework involves enabling the Validator plug-in, configuring Validator’s two configuration files, and creating Form Beans that extend the Validator’s ActionForm subclasses. The following sections explain in detail how to configure and use Validator.

Create a Struts project

Create a struts web application project. I assume you have working environment set for a Struts project. If not then go through the tutorial: Creating Struts application using Eclipse and create a struts project.

Create Form Beans

Create a form bean in your project called CustomerForm and copy following code in it.
package net.viralpatel.struts.validation.form; import org.apache.struts.validator.ValidatorForm; public class CustomerForm extends ValidatorForm { private String name; private String telephone; private String email; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Code language: Java (java)
We will use this validator plugin to validate this form. Note that the form bean is extended from class ValidatorForm and not ActionForm as we generally do in Struts project.

Add Validator Plug-in in struts-config.xml

In order to use Validator in our project we need to configure it in struts-config.xml file. For this add following code in your struts-config.xml file.
<!-- Validator Configuration --> <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property >Define validations for the form</h2> <img src="//www.viralpatel.net/app/uploads/validation-xml-file-struts-validator-framework.png" alt="validation.xml file struts validator framework" title="validation-xml-file-struts-validator-framework" width="166" height="151" class="aligncenter size-full wp-image-687" /> Create a file validation.xml in your applications WEB-INF directory. And copy following content in it. <!-- wp:code {"language": "xml"} --><pre class="wp-block-code"><code></code></pre><!-- /wp:code --> <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE form-validation PUBLIC "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN" "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd"> <form-validation> <global> <constant> <constant-name>telephoneFormat</constant-name> <constant-value>^\d{5,10}$</constant-value> </constant> </global> <formset> <form name="CustomerForm"> <field >Struts-config.xml entry for the action</h2> Following is the entry in struts-config.xml file which maps the Action to our Validator form. <!-- wp:code {"language": "xml"} --><pre class="wp-block-code"><code></code></pre><!-- /wp:code --> <form-beans> <form-bean name="CustomerForm" type="net.viralpatel.struts.validation.form.CustomerForm" /> </form-beans> ... ... ... <action-mappings> ... <action path="/customer" name="CustomerForm" validate="true" input="/index.jsp" type="net.viralpatel.struts.validation.action.CustomerAction"> <forward name="success" path="/Customer.jsp" /> <forward name="failure" path="/index.jsp" /> </action> ... </action-mappings>
Code language: HTML, XML (xml)

Configuring ApplicationResources.properties

Struts validation framework uses externalization of the error messages. The messages are stored in a property file (ApplicationResource.properties) and are referred by the key values. Copy following in your ApplicationResource.properties (or MessageResource.properties).
label.name= Name label.email= Email label.telephone= Telephone label.age= Age # general error msgs errors.header=<font size="2"><UL> errors.prefix=<LI><span style="color: red"> errors.suffix=</span></LI> errors.footer=</UL></font> errors.invalid={0} is invalid. errors.maxlength={0} can not be greater than {1} characters. errors.minlength={0} can not be less than {1} characters. errors.range={0} is not in the range {1} through {2}. errors.required={0} is required. errors.byte={0} must be an byte. errors.date={0} is not a date. errors.double={0} must be an double. errors.float={0} must be an float. errors.integer={0} must be an integer. errors.long={0} must be an long. errors.short={0} must be an short.
Code language: HTML, XML (xml)

Create JSP to display the form

Create a JSP file called index.jsp and copy following content in it.
Code language: HTML, XML (xml)
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%> <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%> <html> <head> <title>Struts Validation Framework example.</title> </head> <body> <html:errors /> <html:javascript formName="CustomerForm" /> <html:form action="/customer"> <bean:message key="label.name" /> <html:text >Running the application We are done with our application. Now execute it from any web container (Tomcat in my case) and open in browser. Enter any invalid value in the form and press submit. Post your comments / doubts on this tutorial.

View Comments

  • Hi I read about this CustomerAction but I don't see any codes for that. Can anyone enlighten me? Thanks

  • Hi JJ,
    CustomerAction class file is a normal implementation of Action class that does not have anything special in it. The error handling is done using Validation framework. CustomerAction class will not be invoked in case of any validation errors.

  • Hi All,
    actually when i run this application , i got this exception
    java.lang.NoClassDefFoundError: org/apache/commons/validator/ValidatorResources

    i loaded all necessary jar file but couldnot solve this problem can anyone tell me why this happening.
    Thanks

  • Hi Neeraj,
    Can you give the list of the jars that you have used in the project. Check struts-validation jar and struts.jar file. Open these jars and see if the class ValidatorResources is available. I am very sure the problem is with the jar only.

  • sorry ,
    in my system same this program generate different result it's print the welcome statement which is wrote in MessageResource.properties file . ?
    why this msg is shown ?
    now what can I do .?

Share
Published by
Viral Patel
Tags: Struts struts validator struts-plugin Tutorial validation framework

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago