Struts2 Validation 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 re-displaying 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>

 

Validator Example-

In this chapter we will look into how Struts’s validation framework. At Struts’s core, we have the validation framework that assists the application to run the rules to perform validation before the action method is executed.

Client side validation is usually achieved using Javascript. But one should not rely upon client side validation alone. Best practice suggests that the validation should be introduced at all levels of your application framework. Now let us look at two ways of adding validation to our Struts project.

Here we will take an example of Employee whose name, age, email and telephone would be captured using a simple page and we will put two validation to make sure that use always enters a name, age should be in between 18 and 65 email should be valid telephone should be valid.

Struts2 Validation With Example

In this example we will see how we can validate a employee page using Struts 2. Let’s first create the employee page. We use Struts UI tags to create the employee page. The <s:head /> tag should be placed in the head section of the HTML page. The s:head tag automatically generates links to the css and javascript libraries that are necessary to render the form elements.

So let us start with the main JSP page of the example.

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Employee Form - Struts2 Demo | dineshonjava.com</title>
<s:head />
</head>
 
<body>
<h2>Employee Form</h2>
 
<s:form action="employee" method="post" validate="true">
    <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="addEmployee" key="label.add.employee" align="center" />
</s:form>
</body>
</html>

myapp.properties

name= Name
age= Age
email= Email
telephone= Telephone
label.add.employee=Add Employee
 
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}.

For this tutorial, we will create an Action class called EmployeeAction which will contain few fields. Create a file EmployeeAction.java in package com.dineshonjava.struts2.action

package com.dineshonjava.struts2.action;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author Dinesh Rajput
 *
 */
public class EmployeeAction extends ActionSupport {

 private static final long serialVersionUID = 1L;
 private String name;
    private Integer age;
    private String email;
    private String telephone;
    
    public String addEmployee() {
        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 EmployeeAction class has fields name, email, telephone and age. Also it has a method called addEmployee() which doesn’t have any logic, it just return SUCCESS.

Configuration file-
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.

<?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.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.custom.i18n.resources" value="myapp" />
 
    <package name="default" extends="struts-default" namespace="/">
        <action name="employee" class="com.dineshonjava.struts2.action.EmployeeAction">
            <result name="success">/success.jsp</result>
      <result name="input">/employee.jsp</result>
          <result name="error">/error.jsp</result>
        </action>
    </package>
   
</struts>

Note that we are mapping the EmployeeAction class with name employee. Also on success user will be redirected to success.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 employee.jsp in case of any errors.
success.jsp

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

index.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome Page - Struts2 Demo | dineshonjava.com</title>
</head>
<body>
<s:a href="employee.jsp">Add Employee</s:a>
</body>
</html>

Adding Validation Logic

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

  • Name field is mandatory
  • Age field is mandatory. It should be a number between 18 and 65.
  • Email field is mandatory. It should be a valid email address.
  • 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 EmployeeAction-validation.xml. Note that this file should be present in the same package as of action class.

Create file EmployeeAction-validation.xml in package com.dineshonjava.struts2.action

<!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="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">18</param>
            <param name="max">65</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>

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 employee.jsp and add validate=”true” in form tag. Struts2 automatically generates the JavaScript code for client side validation of form.

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

Now, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access

URL http://localhost:8080/doj/index.jsp.
This will give you following screen:

Struts2 Validation

click on Add Employee link then you got the following
URL http://localhost:8080/doj/employee.jsp

Struts2 Validation

Employee error page because of validation fails

Struts2 Validation


Employee page on success

Struts2 Validation

Download Source Code
Struts2Validation.zip

 

<<Previous <<   || Index ||   >>Next >>
Previous
Next

One Response

  1. Anonymous December 12, 2013