Part 3: Struts2 Validation Framework

March 27, 2011 at 2:29 pm Leave a comment

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.Validatorand 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 pathcom/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.

1
2
3
4
5
6
7
<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.

1
2
3
4
5
6
<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

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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 calledaddCustomer() 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.

1
2
3
4
5
<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

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
<%@ 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

01
02
03
04
05
06
07
08
09
10
11
<%@ 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.

1
<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.

01
02
03
04
05
06
07
08
09
10
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

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?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.

1
2
3
<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)

 

Entry filed under: struts 2. Tags: .

Part 2: Create Struts 2 Application in Eclipse(using validate and i18n) Part 4: Struts 2 Tiles Plugin Tutorial with Example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed



%d bloggers like this: