Struts Validation Framework Tutorial With Example

Overview of Validation Framework

  • When you are implementing Struts based application you need to implement some code to validate the input(incoming) data.We can validate the input data by overriding validate() method in FormBean class.We need to implement the validation logic inside the validate() method.

  • Lot of fields that we validate require same logic to validate them.you need to write same code repeatedly in every validate() method hence code is unnecessarily duplicated.

  • To avoid this problem and to simplify the validation handling, Apache has introduced validation framework.Validation framework is not a part of struts frame work ,it should be integrated into the struts explicitly.

Overview of Validation Framework

  • When you are implementing Struts based application you need to implement some code to validate the input(incoming) data.We can validate the input data by overriding validate() method in FormBean class.We need to implement the validation logic inside the validate() method.

  • Lot of fields that we validate require same logic to validate them.you need to write same code repeatedly in every validate() method hence code is unnecessarily duplicated.

  • To avoid this problem and to simplify the validation handling, Apache has introduced validation framework.Validation framework is not a part of struts frame work ,it should be integrated into the struts explicitly.






  • The Validator framework allows us to move all the validation logic completely outside of the ActionForm and declaratively configure it for an application through external XML files.

  • No validation logic is necessary in the ActionForm, which makes your application easier to develop and maintain because all validation we are managing through external xml files.Without validation framework you need to write validation logic in ActionForm class.If you need to modify or enhance the validation that occurs for an ActionForm, then the source code must be recompiled and your server must be restarted.This will create a maintenance problem.
  • 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.

  • The Validator Framework in Struts consist of two XML configuration files. The first one is the validator-rules.xml file which contains the default Struts pluggable validator definitions.If you want to create new validation, You can add new validation rules by adding an entry in this file.
    The second one is the validation.xml file which contain details regarding the validation rules that are applied to the different Form Beans. These two configuration file should be place inside the /WEB-INF folder of the application.

Steps to integrate and use validation framework in struts framework :

  • Add Validator Plug-in in struts-config.xml
  • Configuring Validator's configuration files validator-rules.xml and validation.xml
  • Creation of Form Beans that extend the Validator's ActionForm subclasses.

The following Example explain in detail how to configure and use Validator framework in struts.

Step 1 : Create Dynamic Web Project

Create a Dynamic Web Project named StutsValidationExample in Eclipse and add the required jar files to the Project.I assume you have a working environment set for a Struts project. If not then go through the tutorial: Creating Struts application using Eclipse and create a project.



Step 2 : Create Form Beans

Create a form bean in your project called EmployeeForm in the package com.jwt.struts.form and copy following code in it.

EmployeeForm.java
package com.jwt.struts.form;

import org.apache.struts.validator.ValidatorForm;

public class EmployeeForm extends ValidatorForm {
	String username;
	String password1;
	String password2;
	String email;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword1() {
		return password1;
	}

	public void setPassword1(String password1) {
		this.password1 = password1;
	}

	public String getPassword2() {
		return password2;
	}

	public void setPassword2(String password2) {
		this.password2 = password2;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}

In the above code our FormBean is extended from class ValidatorForm and not ActionForm as we generally do in Struts project.So If you want to use validation framework in struts,your class must be extended from ValidatorForm or DynaValidatorForm.

Step 3 : Add Validator Plug-in in struts-config.xml :

To use the validator plug-in the first step is to add it in the Struts configuration files as shown below. The plug-in should be added after any message resource elements in the struts configuration file as shown below.

<!-- Validator Configuration --> 
<plug-in className="org.apache.struts.validator.ValidatorPlugIn"> 
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml, /WEB-INF/validation.xml"/> 
</plug-in>

Step 4 : Define validations for the form :

Create a file validation.xml in your applications WEB-INF directory. And copy following code in it.

validation.xml
<!DOCTYPE form-validation PUBLIC
        "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN"
        "http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd">

<form-validation>
	<formset>
		<form name="employeeForm">
			<field property="username" depends="required,maxlength,minlength,mask">

				<msg name="required" key="error.user.username.required" />
				<msg name="maxlength" key="error.user.username.length" />
				<msg name="minlength" key="error.user.username.length" />
				<msg name="mask" key="error.user.username.invalid" />

				<arg name="maxlength" key="${var:minlength}" position="0"
					resource="false" />
				<arg name="maxlength" key="${var:maxlength}" position="1"
					resource="false" />

				<arg name="minlength" key="${var:minlength}" position="0"
					resource="false" />
				<arg name="minlength" key="${var:maxlength}" position="1"
					resource="false" />

				<var>
					<var-name>minlength</var-name>
					<var-value>3</var-value>
				</var>
				<var>
					<var-name>maxlength</var-name>
					<var-value>15</var-value>
				</var>

				<var>
					<var-name>mask</var-name>
					<var-value>^[a-zA-Z0-9-_]*$</var-value>
				</var>

			</field>

			<field property="password1" depends="required,maxlength,minlength,mask">

				<msg name="required" key="error.user.password.required" />
				<msg name="maxlength" key="error.user.password.length" />
				<msg name="minlength" key="error.user.password.length" />
				<msg name="mask" key="error.user.password.invalid" />

				<arg name="maxlength" key="${var:minlength}" position="0"
					resource="false" />
				<arg name="maxlength" key="${var:maxlength}" position="1"
					resource="false" />

				<arg name="minlength" key="${var:minlength}" position="0"
					resource="false" />
				<arg name="minlength" key="${var:maxlength}" position="1"
					resource="false" />

				<var>
					<var-name>minlength</var-name>
					<var-value>7</var-value>
				</var>
				<var>
					<var-name>maxlength</var-name>
					<var-value>15</var-value>
				</var>

				<var>
					<var-name>mask</var-name>
					<var-value>^[a-zA-Z0-9]*$</var-value>
				</var>

			</field>

			<field property="password2" depends="validwhen">

				<msg name="validwhen" key="error.user.password2.dismatch" />

				<var>
					<var-name>test</var-name>
					<var-value>
						(password1 == *this*)
					</var-value>
				</var>
			</field>

			<field property="email" depends="required,email">

				<msg name="required" key="error.user.email.required" />
				<msg name="email" key="error.user.email.invalid" />

			</field>

		</form>
	</formset>
</form-validation>

Each <formset> tag can contain multiple <form> tags. Specify the form name that you want to associate with the Validation Framework as the value of the name attribute of the form tag. Name of the form specified here should be same as the one specified in the struts-config.xml file.

Now you can associate each properties of the form bean with one or more predefined validation rules . The depends attribute of the field tag takes comma-delimited list of rules to associate with each property.

The username,password,email and phone property is associated with the "required" rule which means that the value cannot be empty. The error message to be displayed when a particular rule is not satisfied is specified in the ApplicationResource.properties file.

The "required" validator will make sure the filed is not blank, and "email" validator is used to check the correct email format. Both "required" and "email" validators are declared in "validator-rules.xml" file.

Note:- Copy validator-rules.xml file inside WEB-INF directory.We are going to use struts provided validation so no need to update validator-rules.xml file.

These configuration has been done in struts-config.xml file

All the configuration regarding the action will be made as in the file struts-config.xml mentioned bellow.

Step 5 : Create Action class :

Create Action class named EmployeeAction in package com.jwt.struts.action package and add below lines of code in that class.

EmployeeAction.java
package com.jwt.struts.action;

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

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class EmployeeAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		return mapping.findForward("success");
	}
}

Step 6 : Struts-config.xml entry for the action :

Create one file named struts-config.xml inside WEB-INF directory and add below line of code into this file.Following is the entry in struts-config.xml file which maps the Action to our Validator form.

struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<form-beans>
		<form-bean name="employeeForm" type="com.jwt.struts.form.EmployeeForm" />
	</form-beans>

	<action-mappings>

		<action path="/Register" type="com.jwt.struts.action.EmployeeAction"
			name="employeeForm" input="/pages/EmployeeRegister.jsp">

			<forward name="success" path="/pages/success.jsp" />

		</action>

		<action path="/RegisterUserPage" type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/EmployeeRegister.jsp" />

	</action-mappings>

	<message-resources parameter="com.jwt.struts.action.ApplicationResource" />


	<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
		<set-property property="pathnames"
			value="/WEB-INF/validator-rules.xml, /WEB-INF/validation.xml" />

	</plug-in>

</struts-config>

Step 7 : 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 file and place inside com.jwt.struts.action package.

Please note that we can provide any name to properties file and we can place this file in any location of your project.We need to provide the path of this file in struts-config.xml file.

ApplicationResources.properties
#user label message

label.user.username = UserName
label.user.password1 = Password
label.user.password2 = Confirm Password
label.user.email = Email

label.user.button.submit = Submit

#Error message
error.user.username.required = Username is required.
error.user.username.length = Username length should be between {0} and {1}.
error.user.username.invalid = Username is invalid , it should be a-z, A-Z, 0-9, dash "-" or underscore "_".

error.user.password.required = Password is required.
error.user.password.length = Password length should be between {0} and {1}.
error.user.password.invalid = Password is invalid , it should be a-z, A-Z, 0-9.

error.user.password2.dismatch = Confirm password is not match.

error.user.email.required = Email is required.
error.user.email.invalid =  Email address is invalid.

Step 8 : Create JSP to display the UI to the user :

Create a folder inside Web-Content directory of the project and provide the folder name as pages.Now create two jsp files EmployeeRgister.jsp and sucess.jsp inside that folder.

EmployeeRgister.jsp
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<html>
<head>
</head>
<body>

	<h2>Struts - Validator Example</h2>

	<b>User Registeration Form</b>
	<br />
	<br />

	<font color="red"> <html:errors />
	</font>

	<html:form action="/Register">

		<br>
		<bean:message key="label.user.username" /> : 
<html:text property="username" size="25" />
		<br>
		<bean:message key="label.user.password1" /> : 
<html:text property="password1" size="25" />
		<br>
		<bean:message key="label.user.password2" /> : 
<html:text property="password2" size="25" />
		<br>
		<bean:message key="label.user.email" /> : 
<html:text property="email" size="25" />
		<br>
		<br>
		<html:submit>
			<bean:message key="label.user.button.submit" />
		</html:submit>

	</html:form>

</body>
</html>
success.jsp
<html>
<head>
</head>
<body>

<h2>Struts - Validator Example</h2>

Employee added successfuly

</body>
</html>

Step 8: Create web.xml

Create web.xml file inside WEB-INF folder and add following code into this.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
        <init-param>
            <param-name>config</param-name>
            <param-value>/WEB-INF/struts-config.xml</param-value>
        </init-param>
        <init-param>
            <param-name>debug</param-name>
            <param-value>2</param-value>
        </init-param>
        <init-param>
            <param-name>detail</param-name>
            <param-value>2</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
        </servlet>
    <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>EmployeeRgister.jsp</welcome-file>
        </welcome-file-list>
    <jsp-config>
        <taglib>
            <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
            <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
        </taglib>
        <taglib>
            <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
            <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
        </taglib>
        <taglib>
            <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
            <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
        </taglib>
        <taglib>
            <taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri>
            <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
        </taglib>
        <taglib>
            <taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
            <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
        </taglib>
        </jsp-config>
    </web-app>

Step 10 : Run the application :

To run the project, right click on Project name from Project Explorer and select Run as -> Run on Server (Shortcut: Alt+Shift+X, R)

Register Page :

Struts Validation Framework

Validation Error :

Enter any invalid value in the form and press submit.

Struts Validation Framework

Success Page :

If you are entering valid data,you can forward to success page

Struts Validation Framework

Error Page :

Struts Application in Eclipse

Directory Structure Of the Project

Directory Structure of the project is given below.

Struts Validation Framework

You can download the source code of the example by clicking on the Download link below.

Download this example(src+lib) developed in eclipse



comments powered by Disqus