Struts 2 Validation Example using Validate Method and XML File


In this Struts 2 tutorial, you will learn how to validate the input of the form using struts validation. You can validate the input of form in two ways.

  1. By using the validate method and
  2. XML file.

Dependencies Required

To works with Struts 2 validation, all the core JAR of Struts 2 is required. To resolve the JAR dependency, you add the following dependency on your pom.xml.

pom.xml
<dependencies>
    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-core</artifactId>
        <version>2.3.16</version>
    </dependency>
</dependencies>

Or you can directly download from Struts website click here.

I prefer to use XML based validation because you have predefined set of validation and you don’t need to create any logic to validate forms input data.

Software Used

In our example, we have used the following software.

  1. Eclipse IDE
  2. Tomcat 8
  3. JDK 8

1- By using Validate Method

Struts 2 provides an interface Validatable and ValidationAware implemented by the ActionSupport class. We can override the validate() method of Validateable interface to perform the validation.

The ValidationAware interface can accept the field level or action class level error messages. The field level messages are kept in Map and Action class level messages are kept in the collection. It should be implemented by the action class to add an error message.

DefaultWorkflowInterceptor

An interceptor that makes sure there are not validation errors before allowing the interceptor chain to continue. This interceptor does not perform any validation.

This interceptor also supports the following interfaces which can implemented by actions:

  • ValidationAware – implemented by ActionSupport class
  • ValidationWorkflowAware – allows changing result name programmatically
  • ValidationErrorAware – notifies action about errors and also allow change result name

You can also use InputConfig annotation to change result name returned when validation errors occurred.

Interceptor parameters:

  • inputResultName – Default to input. Determine the result name to be returned when an action/field error is found.

Project Structure in Eclipse

Take a look of project structure in Eclipse IDE.

Struts 2 Validation Example using Validate Method and XML File

Add Struts 2 Filter

Define the Struts 2 filter in web.xml

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>Struts2ValidationMethod</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<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>

Action Class

Create an action class and override the validate() method of an interface Validatable.

CustomerAction.java
package org.websparrow.action;

import com.opensymphony.xwork2.ActionSupport;

public class CustomerAction extends ActionSupport {
	private static final long serialVersionUID = -7005487231574582188L;

	// Generate getters and setters...
	private String firstName;
	private String lastName;
	private String msg;

	@Override
	public void validate() {
		if (firstName.trim().equals("")) {
			addFieldError("firstName", "First name can't be blank.");
		}
		if (lastName.trim().equals("")) {
			addFieldError("lastName", "Last name can't be blank.");
		}
	}

	@Override
	public String execute() throws Exception {
		msg = firstName + " " + lastName + " added successfully.";
		return "SUCCESS";
	}
}

Mapping Action Class in struts.xml

Map the action classes and result in the struts.xml

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>
	<constant name="struts.devMode" value="true" />
	<package name="default" namespace="/" extends="struts-default">
		<action name="validate" class="org.websparrow.action.CustomerAction">
			<result name="input">/index.jsp</result>
			<result name="SUCCESS">/welcome.jsp</result>
		</action>
	</package>
</struts>

JSP Pages

Create the JSP pages for the user interface.

index.jsp
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
	<h1>Struts 2 Validate Method Example</h1>
	<s:actionerror />
	<s:form action="validate">
		<s:textfield name="firstName" label="First Name"></s:textfield>
		<s:textfield name="lastName" label="Last Name"></s:textfield>
		<s:submit value="Save"></s:submit>
	</s:form>
</body>
</html>
welcome.jsp
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
	<h1>Struts 2 Validate Method Example</h1>	
	<p>Congratulation, <s:property value="msg" /></p>	
</body>
</html>

Output:

Now deploy the project inside Tomcat webapps folder. You will get the following results.

Screen 1

Struts 2 Validation Example using Validate Method and XML File

Screen 2

Struts 2 Validation Example using Validate Method and XML File

2- By using XML File

Form input can also be validated by placing the XML file parallel/next to the action class. Struts 2 XML based validation is fast as compared to validate() method. XML based validation provides more option to validate forms input like:

  1. string validation
  2. email validation
  3. length validation
  4. int validation, etc.

Naming XML File: Make sure the name of XML file must starts with action class name dash validation.xml
e.g ActionClass-validation.xml.

Project Structure in Eclipse

Struts 2 Validation Example using Validate Method and XML File

Define Filter

web.xml file remains same as define above. No changes are required except display-name.

Action Class

You don’t need to override the validate() method in XML based validation. Simply create an action class and override the execute() method and return the SUCCESS.

LoginAction.java
package org.websparrow;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

	private static final long serialVersionUID = -4699529185023717636L;
	private String user, pass;

	public LoginAction() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public String execute() throws Exception {
		return "SUCCESS";
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPass() {
		return pass;
	}

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

Validation XML File

Now create the validation XML file and place it to parallel/next to the action class and the must be same as [ActionClassName-validation.xml].

LoginAction-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="user">
        <field-validator type="requiredstring">
            <message>User Name is required.</message>
        </field-validator>
    </field>
    <field name="pass">
        <field-validator type="requiredstring">
            <message>Password is required.</message>
        </field-validator>
    </field>
</validators>

JSP Pages

Create the JSP page for user interaction.

index.jsp
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<s:head />
</head>
<body>
	<h1>Struts2 XML File Validation Example</h1>	
	<s:form action="xmlvalidation">
		<s:textfield name="user" label="User Name"></s:textfield>
		<s:password name="pass" label="Password"></s:password>
		<s:submit value="Login"></s:submit>
	</s:form>
</body>
</html>
welcome.jsp
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome</title>
</head>
<body>
	<h1>Struts2 XML File Validation Example</h1>	
	<p> Hello, <s:property value="user" /> </p>
</body>
</html>

Output:

Now deploy the project inside the Tomcat webapps folder. You will get the following results.

Screen 1

Struts 2 Validation Example using Validate Method and XML File

Screen 2

Struts 2 Validation Example using Validate Method and XML File

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.