Home » Enterprise Java » Struts 2 » Struts Validation Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Struts Validation Example

To ensure users are entering valid information, validation of form’s input is necessary for every web application. The struts2 framework provides built-in robust validation framework which is highly decoupled from the view and controller, thus it can be easily integrated with the existing applications. In this tutorial, we will see how Struts2 validation works by creating a sample application that validates the user’s input for a login form.

1. Introduction

1.1 Struts Framework

  • Struts framework is based on a set of Java technologies like Servlet, JSP, JSTL, XML, Velocity etc which provides the MVC (i.e. Model View Controller) implementation and a ready to use Validation framework
  • The power of Struts lies in its model layer by which it can be integrated with other Java technologies, for e.g.: JDBC, EJB, Spring, Hibernate etc
  • Struts framework is a complete web framework as it provides the Web Form Components, Validators, Error Handling, Internationalization, Tiles and its own Controller component
  • Struts2 framework also supports the annotation based configurations which are easy to use and are more intuitive
  • Struts2 also comes with powerful APIs to configure the Interceptors that greatly reduce the coupling in an application

1.1.1 How Struts2 Work?

When developers use Struts, the framework provides them with a Controller Servlet i.e. ActionServlet which is defined in the Struts libraries that are included in an application. This controller servlet is automatically registered in the deployment descriptor file (web.xml) as shown in the below figure.

Fig. 1: Struts2 Request Response Overview

Fig. 1: Struts2 Request Response Overview

The controller servlet uses a struts-config.xml file to map the incoming requests to the Struts Action objects and instantiate any ActionForm object associated with the action to temporarily store the form data. The Action Object processes requests by using its execute() method while making the use of any stored data. Once the Action Object processes a request, it stores any new data in the same or a different result bean and forwards the response to an appropriate view.

1.2 Struts2 Validation Framework

Struts2 action relies on a validation framework provided by the XWork to enable the application’s input validation rules for the actions before they are actually executed. This framework allows developers to separate the validation logic from the actual Java or the JSP code, where it can be reviewed and easily modified later.

The Struts2 Validation framework alleviates much of a headache associated with the data validation and allows developers focus on the validation logic and not on the mechanics of capturing data and re-displaying the incomplete or the invalid data.

The validation framework comes with a set of useful routines to handle the form validations automatically and it can handle by both server as well as the client side (usually achieved by using jQuery or Javascript) form validations. If certain validation is not present, developers can create their own validation logic by implementing Java interface (i.e. com.opensymphony.xwork2.Validator) and plug it into the validation framework as a re-usable component.

By default, the validation framework is enabled in Struts2 so developers don’t have to do anything to use it, except creating the validation rules in an XML file and putting it in the right place. Developers specify the validation rules per action class in an XML file that follows either of the below naming conventions:

  • <actionClass>-validation.xml
  • <actionClass>-<actionAlias>-validation.xml

Where actionClass is the class name of the action, and the actionAlias is the name of the action element specified in Struts2 configuration file (i.e. struts.xml). This XML contains the validation rules using the validators and must be placed at the same location as the action class.

1.2.1 Struts2 Validator Scope

There are two types of validators in the Struts2 Validation Framework:

  • Field Validators: These are used to perform the validation checks on a single field. The field is declared in the action class or in a Java-bean associated with the action class. A field validator is declared using the <field-validator /> element. Here is an example of a field validator for a field named email:
    <field name="email">
        <field-validator type="email">
            <message>Please Enter A Valid Email Address</message>
        </field-validator>
    </field>
    
  • Non-Field Validators (or Plain Validators): These are used to perform the validation checks on a set of fields or no field at all, however, the disadvantage of this approach is that developers can’t apply many validators to a single field. A non-field validator is declared using the <validator /> element. Here is an example of a non-field validator which compares two numbers:
    <validator type="expression">
        <param name="expression">x > y</param>
        <message>x must be greater than y, x = ${x}, y = ${y}</message>
    </validator>
    

Do note, it is recommended to use the Field Validators because it provides more flexibility. Now, open up the Eclipse IDE and let’s see how to implement a simple hello world application in the struts2 framework!

2. Struts2 Validation Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 2: Struts2 Validation Structure

Fig. 2: Struts2 Validation Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 3: Create Maven Project

Fig. 3: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 4: Project Details

Fig. 4: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

Fig. 5: Archetype Selection

Fig. 5: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 6: Archetype Parameters

Fig. 6: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Struts2ValidationExample</groupId>
	<artifactId>Struts2ValidationExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

We can start adding the dependencies that developers want like Struts2 Core etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependency for the Struts2 framework. The rest dependencies will be automatically resolved by Maven, such as Struts2 Core, OGNL etc. The updated file will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Struts2ValidationExample</groupId>
	<artifactId>Struts2ValidationExample</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<!-- Servlet API Dependency -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
		<!-- Struts2 Core Framework Dependency -->
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>2.3.24.1</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.2 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 7: Java Package Creation

Fig. 7: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.struts2.validation.

Fig. 8: Java Package Name (com.jcg.struts2.validation)

Fig. 8: Java Package Name (com.jcg.struts2.validation)

Once the package is created in the application, we will need to create the Struts2 action class. Right-click on the newly created package: New -> Class.

Fig. 9: Java Class Creation

Fig. 9: Java Class Creation

A new pop window will open and enter the file name as: LinkAction. The action class will be created inside the package: com.jcg.struts2.validation.

Fig. 10: Java Class (LinkAction.java)

Fig. 10: Java Class (LinkAction.java)

3.2.1 Implementation of Action Class

Actions are the core of the Struts2 framework, as they are for any Model View Controller framework. But the action servers in two important capacities i.e.

  • First, the action class is not required to implement any interface or extend any class
  • Second, the action class is required to create an execute() method to put all the business logic inside and return a string value to tell the application where to redirect

This action class will redirect the client to the success page if the email is admin@jcg.com, otherwise it will redirect back to the error page. Add the following code to it:

LinkAction.java

package com.jcg.struts2.validation;

import com.opensymphony.xwork2.ActionSupport;

public class LinkAction extends ActionSupport {	

	private String uname, pass, mail;
	private static final long serialVersionUID = 1L;

	public String getUname() {
		return uname;
	}

	public void setUname(String uname) {
		this.uname = uname;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public String getMail() {
		return mail;
	}

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

	// All Struts Business Logic Goes Here In This Method
	public String execute() {
		if((uname != null && uname.equalsIgnoreCase("jcg")) && (pass != null && pass.equalsIgnoreCase("jcg@123")) && 
				(mail != null && mail.equalsIgnoreCase("admin@jcg.com"))) {
			return SUCCESS;
		} else {
			return ERROR;
		}		
	}
}

3.3 Configuration Files

Let’s write all the configuration files involved in this application.

3.3.1 Struts Configuration File

To configure the struts2 framework, developers need to implement a configuration file i.e. struts.xml. In this file, we will define the result tag which maps a particular action with a JSP page. Right-click on the src/main/resources folder, New -> Other.

Fig. 11: XML File Creation

Fig. 11: XML File Creation

A new pop window will open and select the wizard as an XML file.

Fig. 12: Wizard Selection

Fig. 12: Wizard Selection

Again, a pop-up window will open. Verify the parent folder location as: Struts2ValidationExample/src/main/resources and enter the file name as: struts.xml. Click Finish.

Fig. 13: struts.xml

Fig. 13: struts.xml

Once the XML file is created, we will add the following code to it:

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<!-- Enables Dynamic Method Invocation To Customize The Default 'execute()' Method In The Controller -->
	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
	
	<!-- Struts2 Action Mapping -->
	<package name="default" extends="struts-default">
		<action name="login" class="com.jcg.struts2.validation.LinkAction"> 
       		<result name="error">/error.jsp</result>
            <result name="success">/success.jsp</result>
            <result name="input">/index.jsp</result>
        </action>
	</package>
</struts>

3.3.2 Validator Configuration File

To specify the validation rules for the login form, we will create the LinkAction-validation.xml file under the package: src/main/resources/com/jcg/struts2/validation/ with the following content:

LinkAction-validation.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
	<field name="uname">
		<field-validator type="requiredstring">
			<message>Username Is Required!</message>
		</field-validator>
	</field>
	<field name="pass">
		<field-validator type="requiredstring">
			<message>Password Is Required!</message>
		</field-validator>
	</field>
	<field name="mail">
		<field-validator type="requiredstring">
			<message>Email Is Required!</message>
		</field-validator>
		<field-validator type="email">
			<message>Enter A Valid Email Address!</message>
		</field-validator>
	</field>
</validators>

Here we have specified the field validators for the three fields of the login form with validator types of requiredstring and email. The text inside the <message /> element will be shown to the user if he/she types in the invalid data. For e.g. Wrong email format or the empty strings.

3.3.3 Web Deployment Descriptor

The web.xml file declares a filter (i.e. StrutsPrepareAndExecuteFilter) to configure the struts2 framework in the application. Add the following code to it:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
	<display-name>Struts 2 Web Application</display-name>
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

3.4 Creating JSP View

Let us write a simple JSP to illustrate this tutorial. Right-click on Struts2ValidationExample/src/main/webapp folder, New -> JSP File.

Fig. 14: JSP Creation

Fig. 14: JSP Creation

Verify the parent folder location as: Struts2ValidationExample/src/main/webapp and enter the filename as: index.jsp. Click Finish.

Fig. 15: index.jsp

Fig. 15: index.jsp

Repeat the step (i.e. Fig. 14) and create the following new JSP files i.e.

  • success.jsp
  • error.jsp

3.4.1 Application’s Input Form

A login page uses the struts2 tags for displaying the username, email and password input fields along with a login button. Add the following code to it:

index.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	    <title>Struts2 Validation Example</title>
	    <style type="text/css">
	    	#loginFormDiv {
	    		margin-top: -24px !important;
	    	}
	    	.errorMessage {
	    		color: red !important;
	    	}
	    </style>
	</head>
	<body>
	    <div align="center">
	    	<h3><u>Struts2 Validation Using Xml Example</u></h3>
	    	<div id="loginFormDiv">
		    	<s:form action="login" id="validationLoginFormId">
			        <s:textfield id="nameId" name="uname" label="Enter Username" /> 
			        <s:textfield id="emailId"  name="mail" label="Enter Email" /> 
			        <s:password id="passId" name="pass" label="Enter Password" /> 
			        <s:submit value="Login" align="center" />
			    </s:form>
		    </div>
	    </div>
	</body>
</html>

Client Side Validation

The attribute validate=”true” of the <s:form /> tag specifies that the form validation will take place on the client side.

<s:form action="login" validate="true" />

Struts2 will generate the appropriate Javascript code to perform the client-side validation.

Server-Side Validation

Without specifying the attribute validate=”true”, Struts2 will perform the validation checks at the server-side.

<s:form action="login" />

Here, no Javascript code will be generated but instead, every submission will be sent to the server for the validation.

3.4.2 Application’s Success Page

This page will be picked up if the login form passes the validation checks and the user enters the desired login credentials. Add the following code to it:

success.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	    <title>Struts2 Validation Example</title>
	    <style type="text/css">
	    	#welcomeNameSpan {
	    		text-transform: capitalize;
	    		color: green;
	    	}
	    </style>
	</head>
	<body>
		<h3>Welcome <span id="welcomeNameSpan"><s:property value="uname"/></span>, You Are Successfully Logged In!</h3>
		</body>
</html>

3.4.3 Application’s Error Page

This page will be picked up if the user has entered the invalid login credentials. Add the following code to it:

error.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <title>Struts2 Validation Example</title>
   </head>
   <body>
      <h3><span style="color: red;">Unauthorised Access! Please Enter Valid Credentials!</span></h3>
   </body>
</html>

4. Run the Application

As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 16: How to Deploy Application on Tomcat

Fig. 16: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page (i.e. the login form) will be displayed.

http://localhost:8085/Struts2ValidationExample/

Server name (localhost) and port (8085) may vary as per your Tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 17: Login Form Page

Fig. 17: Login Form Page

Don’t type anything, just hit the Login button. The validation error messages will be displayed above the fields.

Fig. 18: Error Messages

Fig. 18: Error Messages

Now enter any random username, email address (in the wrong format) and a password. Click on Login button.

Fig. 19: Email Format Error Message

Fig. 19: Email Format Error Message

Now enter the correct login credentials (i.e. Username: jcg, Password: jcg@123, and Email: admin@jcg.com) and click on the Login button, users will be redirected to the success page if everything is fine with the application.

Fig. 20: Success Page

Fig. 20: Success Page

That’s all for this post. Happy Learning!

6. Conclusion

In this tutorial, developers learned how to download, create a new project in Eclipse IDE, and add Struts2 libraries to write a simple struts2 validation framework tutorial. That’s all for this tutorial and I hope this article served you whatever you were looking for.

7. Download the Eclipse Project

This was an example of struts2 validation for the beginners.

Download
You can download the full source code of this example here: Struts2ValidationExample
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of