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

 

1. The Struts2 Validation Framework

By default, the validation framework is included in Struts2 default stack and is “turned on” already so we don’t have to do anything to use it, except creating validation rules in an XML file in a correct manner and putting it into right place. We specify validation rules per action class in an XML file that follows either of these naming conventions:

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

Where actionClass is Java class name of the action, and actionAlias is name of the action element specified in struts.xml file. For example:

    • LoginAction-validation.xml
    • LoginAction-doLogin-validation.xml

This XML file must be placed in the classpath, under same location as the action class. Inside this XML file we specify validation rules using validators. There are two types of validator in Struts2:

    • Field Validators: are used to perform validation checks on a single field. The field is declared in the action class or in a JavaBean associated with the action class. A field validator is declared using <field-validator> element.
    • Non-Field Validators (or Plain Validators): are used to perform validation checks on a set of fields or none field at all. A non-field validator is declared using <validator> element.

Here’s an example of a field validator for a field named “email”:

<field name="email">
	<field-validator type="email">
	    <message>You must enter a valid e-mail address</message>
	</field-validator>
</field>

 

And this is an example of a non-field validator which compares two numbers x and y:

<validator type="expression">
	<param name="expression">x &gt; y</param>
	<message>x must be greater than y, x = ${x}, y = ${y}</message>
</validator> 

 

To see a complete list of built-in validators in Struts2: Bundled Validators.

Now let’s see how to build the sample application that applies the validation framework.


2. Coding Input Form

Create LoginForm.jsp file with the following content:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="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>Login Form - Struts2 Validation Example</title>
</head>
<body>
	<div align="center">
		<h2>Login</h2>
		<s:form action="doLogin" method="post" validate="true">
			<s:textfield label="E-mail" name="email" />
			<s:password label="Password" name="password" />
			<s:submit value="Login" />
		</s:form>
	</div>
</body>
</html>

This page will show a login form with two fields: email and password. We’ll configure Struts to validate these fields.

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="doLogin" method="post" validate="true"> 

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

 

Server-side validation

Without specifying the attribute validate=”true”, Struts will perform validation checks on the server-side:

<s:form action="doLogin" method="post">

No Javascript code will be generated. Instead, every submission will be sent to the server for validating.

 


3. Coding Action Class

Create LoginAction.java file under package net.codejava.struts with the following code:

package net.codejava.struts;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
	private String email;
	private String password;

	public String execute() {
		if (email != null && email.equals("admin@codejava.net")) {
			return SUCCESS;			
		} else {
			return INPUT;
		}
	}
	
	// getters and setters
}

This action class will redirect the client to SUCCESS page if the e-mail is admin@codejava.net, otherwise redirect back to the INPUT page.

 

Recommended Book: Struts 2 in Action


4. Coding Success Page

Create LoginSuccess.jsp file with the following content:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="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>Login Success</title>
</head>
<body>
	<div align="center">
		<h2>Welcome, you have logged in successfully!</h2>
	</div>
</body>
</html>

This page will be picked up if the login form passes validation checks and the user enters the desired e-mail address.

 


5. Configuring Validators

To specify validation rules for the login form, create LoginAction-validation.xml file under package net.codejava.struts with the following content:

<!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="email">
        <field-validator type="requiredstring">
            <message>You must enter an e-mail address</message>
        </field-validator>
        <field-validator type="email">
            <message>You must enter a valid e-mail address</message>
        </field-validator>
    </field>
    
    <field name="password">
        <field-validator type="requiredstring">
            <message>You must enter password</message>
        </field-validator>
    </field>
</validators>

As we can see, we specify field validators for the two fields of the login form, email and password, with validator types of requiredstring and email, respectively. The text inside the <message> element will be shown to the user if he types in invalid data, e.g. wrong e-mail format or empty strings.


6. Configuring struts.xml file

Configure the LoginAction in the struts.xml file as follows:

<?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>

	<package name="Struts2Validation" extends="struts-default" namespace="/">
		<action name="doLogin" class="net.codejava.struts.LoginAction">
			<result name="success" type="redirect">/LoginSuccess.jsp</result>
			<result name="input">/LoginForm.jsp</result>
		</action>
	</package>

</struts>

So far we have completed the sample application. Here’s how the project structure would look like in Eclipse IDE:

Struts2 Validation Basic XML project structure in Eclipse

We use the latest distribution of Struts2 to date, e.g. Struts 2.3.15.1. The required libraries are:

    • commons-fileupload-1.3.jar
    • commons-io-2.0.1.jar
    • commons-lang3-3.1.jar
    • commons-logging-1.1.3.jar
    • commons-logging-api-1.1.jar
    • freemarker-2.3.19.jar
    • javassist-3.11.0.GA.jar
    • ognl-3.0.6.jar
    • struts2-core-2.3.15.1.jar
    • xwork-core-2.3.15.1.jar

 

Recommended Book: Apache Struts 2 Web Application Development


7. Testing the Example Application

Enter the following URL in web browser:

http://localhost:8080/Struts2ValidationBasicXML/LoginForm.jsp

The login form appears as follows:

Testing form validation with Struts2

Don’t type anything, just hit the Login button. Two validation error messages are displayed above the fields:

Test struts2 form validation - error 1

Now try to enter an e-mail address (but in wrong format) and a password, then hit Login. We’ll see:

Test struts2 form validation - invalid email address

Now enter the e-mail as admin@codejava.net and an arbitrary password and hit Login, we’ll be redirected to the success page:

Test struts2 form validation - success page

That works! You can download Eclipse project and deployable WAR file of this application under the Attachments section.

 

Recommended Book: Struts 2 Design and Programming: A Tutorial (A Tutorial series)

Submit to DeliciousSubmit to DiggSubmit to FacebookSubmit to Google BookmarksSubmit to StumbleuponSubmit to TechnoratiSubmit to TwitterSubmit to LinkedIn
Attachments:
Download this file (Struts2ValidationBasicXML.war)Struts2ValidationBasicXML.war[Deployable WAR file]3446 kB
Download this file (Struts2ValidationBasicXML.zip)Struts2ValidationBasicXML.zip[Eclipse project]3450 kB