Over a million developers have joined DZone.

Struts 2 Tutorial: Struts 2 Validation Framework Tutorial with Example

DZone 's Guide to

Struts 2 Tutorial: Struts 2 Validation Framework Tutorial with Example

· Java Zone ·
Free Resource

Welcome to Part-3 of 7-part series of tutorials where we will go through different practical aspects of Struts2 Framework. In the last part we Created a Basic Struts2 Application from Scratch. I strongly recommend you to go through the previous articles in case you are new to Struts2.

In this article we will learn how to leverage Struts2 Validation Framework in an application. For this we will use StrutsHelloWorld application which we created in previous article as base and starts adding validation logic to it.

Introduction to Struts2 Validation Framework

Struts Action 2 relies on a validation framework provided by XWork to enable the application of input validation rules to your Actions before they are executed. Struts2 Validation Framework allows us to separate the validation logic from actual Java/JSP code, where it can be reviewed and easily modified later.

The Struts2 Validation Framework 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.

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 by implementing java interface com.opensymphony.xwork2.Validator and plug it into validation framework as a re-usable component.

Validator uses XML configuration files to determine which validation routines should be installed and how they should be applied for a given application. validators.xml file contains all common validators declaration. If validators.xml file is not present in classpath, a default validation file is loaded from path com/opensymphony/xwork2/validator/validators/default.xml.

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.

Validators Scope

There are two types of Validators in Struts2 Validation Framework.

  1. Field Validators
  2. Non-field validators

Field validators, as the name indicate, act on single fields accessible through an action. A validator, in contrast, is more generic and can do validations in the full action context, involving more than one field (or even no field at all) in validation rule. Most validations can be defined on per field basis. This should be preferred over non-field validation wherever possible, as field validator messages are bound to the related field and will be presented next to the corresponding input element in the respecting view.

<validators>  <field name="bar">      <field-validator type="required">          <message>You must enter a value for bar.</message>      </field-validator>  </field></validators>

Non-field validators only add action level messages. Non-field validators are mostly domain specific and therefore offer custom implementations. The most important standard non-field validator provided by XWork is ExpressionValidator.

<validators>      <validator type="expression">            <param name="expression">foo lt bar</param>            <message>Foo must be greater than Bar.</message>      </validator></validators>

Getting Started

Let us add validation logic to StrutsHelloWorld application that we created in previous article. For this tutorial, we will create an Action class called CustomerAction which will contain few fields. Create a file CustomerAction.java in package net.viralpatel.struts2.
Copy following content into it.

package net.viralpatel.struts2;import com.opensymphony.xwork2.ActionSupport;public class CustomerAction extends ActionSupport{private String name;private Integer age;private String email;private String telephone;public String addCustomer() {return SUCCESS;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getTelephone() {return telephone;}public void setTelephone(String telephone) {this.telephone = telephone;}}

Note that CustomerAction class has fields name, email, telephone and age. Also it has a method called addCustomer() which doesn’t have any logic, it just return SUCCESS.

Now we will add entry for this new action class in struts.xml file. Open the struts.xml file which will be present under resources folder. And add following content between <package></package> tag.

<action name="customer"class="net.viralpatel.struts2.CustomerAction"><result name="success">SuccessCustomer.jsp</result><result name="input">Customer.jsp</result></action>

Note that we are mapping the CustomerAction class with name customer. Also on success user will be redirected to SuccessCustomer.jsp page. Notice that there is another result tag with name input. Whenever the validation logic encounter some validation error, it redirects the user back to page specified as input. Thus in our example, user will be redirected back to Customer.jsp in case of any errors.

Create two new JSPs Customer.jsp (which will contain Customer form) and SuccessCustomer.jsp (which will be displayed on success).

<%@ page contentType="text/html; charset=UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"%><html><head><title>Customer Form - Struts2 Demo | ViralPatel.net</title></head><body><h2>Customer Form</h2><s:form action="customer.action" method="post"><s:textfield name="name" key="name" size="20" /><s:textfield name="age" key="age" size="20" /><s:textfield name="email" key="email" size="20" /><s:textfield name="telephone" key="telephone" size="20" /><s:submit method="addCustomer" key="label.add.customer" align="center" /></s:form></body></html>


<%@ page contentType="text/html; charset=UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"%><html><head><title>Customer Page - Struts2 Demo | ViralPatel.net</title></head><body><h2>Customer Added Successfully.</h2></body></html>

We have created Customer.jsp file which will display Customer form. But we don’t have link to this page from our web application. So we will create a link to Customer.jsp from Welcome.jsp page. Open Welcome.jsp page and add following link code into it.

<s:a href="Customer.jsp">Add Customer</s:a>

Now open the ApplicationResources.properties file from /resources folder and add following key/values in it.

name= Nameage= Ageemail= Emailtelephone= Telephonelabel.add.customer=Add Customererrors.invalid=${getText(fieldName)} is invalid.errors.required=${getText(fieldName)} is required.errors.number=${getText(fieldName)} must be a number.errors.range=${getText(fieldName)} is not in the range ${min} and ${max}.

Execute the code in Eclipse and see the output. You will see login page. Enter username=admin and password=admin123 and do login. On welcome page you will see a link to Add Customer page. Click on that link and you will see Customer page.

Adding Validation Logic

Now we are ready with the basic customer form on which we will add the validation logic. Following will be the validations rules:

  1. Name field is mandatory
  2. Age field is mandatory. It should be a number between 1 and 100.
  3. Email field is mandatory. It should be a valid email address.
  4. Telephone is mandatory.

In order to define validation logic for particular form, we first have to create an XML file which will hold this data. Struts2 define a specific naming convention in defining validation xml files. The format is <ActionClassName>-validation.xml. So for our application we will create a file CustomerAction-validation.xml. Note that this file should be present in the same package as of action class.
Create file CustomerAction-validation.xml in package net.viralpatel.struts2. And copy following content into it.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE validators PUBLIC  "-//OpenSymphony Group//XWork Validator 1.0.2//EN"  "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"><validators><field name="name"><field-validator type="requiredstring"><param name="trim">true</param><message key="errors.required" /></field-validator></field><field name="age"><field-validator type="required"><message key="errors.required" /></field-validator><field-validator type="int"><param name="min">1</param><param name="max">100</param><message key="errors.range"/></field-validator></field><field name="email"><field-validator type="requiredstring"><message key="errors.required" /></field-validator><field-validator type="email"><message key="errors.invalid" /></field-validator></field><field name="telephone"><field-validator type="requiredstring"><message key="errors.required" /></field-validator></field></validators>

And that’s it. We just added validation logic to our example. Note that the validations xml file contains different field-validators.

Client Side Validation

It is very easy to add Client Side validation or JavaScript validation to any form in Struts2. All you have to do is to add validate=”true” in form tag in your JSP file. For example open Customer.jsp and add validate=”true” in form tag. Struts2 automatically generates the JavaScript code for client side validation of form.

<s:form action="customer.action" method="post" validate="true">...</s:form>

That’s All Folks

Execute the application and test the Customer form with different values.
Customer page
Customer page with errors
Customer page on success

Download Source Code

Click here to download Source Code without JAR files (9KB)

Moving On

Now that we have implemented Struts2 Validation framework in our example, we know how exactly struts2 validation is handled. Also we know different types of validators like field-validators and non-field. In next part we will study Tiles framework and implement it in our application.


From: http://viralpatel.net/blogs/

java ,struts2

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}