Viral Patel is a keen technology blogger and enthusiast. Working with a software company, he uses his leisure time to learn and explore emerging areas in tech world. His passion for technology has motivated him from creating an operating system to writing tutorials/articles on Java, JavaEE, Spring, Hibernate, Struts, jQuery, PHP. Visit the website http://viralpatel.net for a wide range of articles and tutorials on these topics. Viral has posted 13 posts at DZone. View Full User Profile

Struts 2 Tutorial: Struts 2 Validation Framework Tutorial with Example

01.16.2010
| 109552 views |
  • submit to reddit
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.

Struts 2 Tutorial List

 
 Related: Struts Validation Framework Tutorial with Example

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.
customer-action-struts2
Copy following content into it.
CustomerAction.java

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).
struts2-validation-jsp-files
Customer.jsp

<%@ 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>

SuccessCustomer.jsp

<%@ 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= Name
age= Age
email= Email
telephone= Telephone
label.add.customer=Add Customer

errors.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.
struts2-customer-form

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.
struts2-validation-xml
CustomerAction-validation.xml

<?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
struts2-customer-form
Customer page with errors
customer-page-validation-errors
Customer page on success
customer-page-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/ 

Published at DZone with permission of its author, Viral Patel.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Maheswaran Jayapal replied on Thu, 2010/07/29 - 1:46am

Hi viral,

         I got error like this for the first program too. Actually whats wrong i did kindly help me.

 

Apache Tomcat/6.0.28 - Error report

HTTP Status 404 - /StrutsHelloWorld2/

type Status report

message /StrutsHelloWorld2/

description The requested resource (/StrutsHelloWorld2/) is not available.

Apache Tomcat/6.0.28

 

 

 

 

Shrinivas Krish... replied on Thu, 2010/08/05 - 3:45am in response to: Maheswaran Jayapal

@Maheshwaran: You'll have to post a lot more information about the tomcat stacktrace you see. if eclipse isn't your forte, export the project as a war file, and manually deploy it to tomcat to check if all required resources (jsp, .resources, class files, web and struts.xml are present in the war)

Nicolas Leuenberger replied on Fri, 2010/08/27 - 10:49pm

What about to validate with wildcards actions?

I have something like 

<package name="BackOffice" namespace="/bo" extends="struts-default">

<action name="*User" class="zzz.UsersAction" method="{1}">

and one method inside UsersAction

public String changeInfo(){

So, the url to reach the changeInfo method will be

http://something.net/bo/changeInfoUser.action

so.. what I have to do to put a validation on this to make field firstName required?

I have tried many ways but none does the trick.

Thanks

PS: I have no file named struts-defaults.xml so I'm working with the struts defaults params.

Sanket Paranjape replied on Mon, 2010/08/30 - 2:16pm in response to: Maheswaran Jayapal

This might  be because you are using latest version of struts. I had got the same error. This tutorial is made on struts 2.0.12. I used 2.0.14 and got it working. I was getting error something like Filter dispatcher not found or something like that. Not so sure

Zulkernain Kanj... replied on Wed, 2011/03/16 - 2:53am

Dear Viral! Kem Che? Hey i would like to validate my fields one by one and once its get right value then only it will validate other one. Apart from it can i alert the message instead of labeling it?

Alex Rodrics replied on Fri, 2011/06/03 - 4:34am

I have copied and pasted the same code provided and I am geting correct results. But i have got following issues too;

 1. CustomerAction-validation.xml    (It is showing referenced file contains errors.)

 2.  I am getting following warning in eclipse console:-

 

       Jun 3, 2011 11:14:23 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 19479 ms
Jun 3, 2011 11:14:47 AM com.opensymphony.xwork2.util.logging.commons.CommonsLogger warn
WARNING: No configuration found for the specified action: 'login.action' in namespace: ''. Form action defaulting to 'action' attribute's literal value.
Jun 3, 2011 11:14:47 AM com.opensymphony.xwork2.util.logging.commons.CommonsLogger warn
WARNING: No configuration found for the specified action: 'login.action' in namespace: ''. Form action defaulting to 'action' attribute's literal value.
Jun 3, 2011 11:19:12 AM com.opensymphony.xwork2.util.logging.commons.CommonsLogger warn
WARNING: No configuration found for the specified action: 'login.action' in namespace: '/'. Form action defaulting to 'action' attribute's literal value.
Jun 3, 2011 11:19:12 AM com.opensymphony.xwork2.util.logging.commons.CommonsLogger warn
WARNING: No configuration found for the specified action: 'login.action' in namespace: '/'. Form action defaulting to 'action' attribute's literal value.

 

I have tried many things for namespace but in vain. Any idea?

 

thanks

 

Duminda Duleep replied on Wed, 2011/06/08 - 3:38am

in CustomerAction-validation.xml file 1st line gave below error Referenced file contains errors (http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd). For more information, right click on the message in the Problems View and select "Show Details..." i thinks this error may be incorrect DOCTYPE of file any one know correct DOCTYPE of CustomerAction-validation.xml

Peter Wkc replied on Mon, 2012/10/01 - 10:29pm

How to customize the validation error message? css or ...

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.