Srikanth Technologies

Using Validation with Struts 2

I have already discussed about how to get started with Struts 2 in my previous blog. If you have not yet got started, read my blog on Getting Started With Struts2.  In this blog I continue to use the same web application.

In this blog, I show you how to use validation with Struts2. We will work with a simple example to understand the steps required to use validation in Struts2.

register.jsp

This page is used to take information from user regarding the registration. The details to be taken and validations to be performed are as follows :


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <body>
        <h2>Registration </h2>
        <s:form action="register">
            <s:textfield  name="username" label="Username "/>
            <s:password name="password" label="Password "/>
            <s:password name="confirmPassword" label="Confirm Password "/>
            <s:textfield name="email"  label="Email Address " />
            <s:textfield name="mobile"  label="Mobile Number " />
            <p/>
            <s:submit value="Register"/>
            <p/>
            <s:actionerror/>     
        </s:form>
    </body>
</html>

RegisterAction.java

RegisterAction is the action class for registration. It contains properties for username, password, confirmPassword, email and mobile. It must extend ActionSupport class to enable validation. It contains execute() method that does the actual process and returns a string which decides the navigation.

package action;

import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport {
    private String username,password,confirmPassword,email,mobile;
    public String getConfirmPassword() {
        return confirmPassword;
    }
    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public RegisterAction() {
    }
    public String execute() throws Exception {
       // do the required process
        return "success";
    }
}

RegisterAction-validation.xml

It is the xml file that defines the validations to be used for RegisterAction class properties. The name of the file is made of <actionclass>-validation.xml. Place this file in the same package as the action class. So in our case, we need to place RegisterAction-validation.xml file in action package as RegisterAction class is also placed in the same package.

In this file we specify which validator is to be used for each field. A field may have more than one validator associated with it. Element <field> is used to specify the field to be used for validation and <field-validator> element specifies the type of validator to be used. Message tag specifies the message to be displayed.

Element <param> is used to provide additional information required for some validators. For example, minimum length for stringlength validator and regular expression for regex validator are provided using <param> element as shown in the .xml file.


<?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="username">
        <field-validator type="requiredstring">
             <message>Username is required </message>
        </field-validator>
   </field>
   <field name="password">
        <field-validator type="requiredstring">
             <message>Password is required </message>
        </field-validator>

        <field-validator type="stringlength">
             <param name="minLength">5</param>
             <message>Password must contain at least ${minLength} characters</message>
        </field-validator>
 </field>
  <field name="email">
        <field-validator type="email">
             <message>Email address is not valid</message>
        </field-validator>
        <field-validator type="requiredstring">
             <message>Email address is required!</message>
        </field-validator>
  </field>

  <field name="mobile">
        <field-validator type="regex">
             <param name="expression">^[0-9]{10}$</param>
             <message>Mobile number must be of 10 digits</message>
        </field-validator>
  </field>

  <validator type="expression">
       <param name="expression">password == confirmPassword</param>
       <message>Password and confirm password do not match!</message>
  </validator>
</validators>

struts.xml

Add the following entries regarding registration action in struts.xml, which is in default package under source packages.


    <action name="register"  class="action.RegisterAction">
            <result name="success">/registered.jsp</result>
            <result name="input">/register.jsp</result>
    </action>
    

registered.jsp

This page is displayed when registration process is successful. It just displays the name of the user who is successfully registered by taking the value from username property.


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Registration Completed</title>
    </head>
    <body>
        Thank you [ <s:property value="username"/>] for registering.
    </body>
</html>

Now run register.jsp and click on submit button. The following screen shows what happens if you don't enter username, password ,email address and enter less than 10 digits in mobile number field.

The last validation specified using <validator> element is used to evaluate a condition that is related to more than one field. So enter password and confirm password differently and you will see a message displayed where <s:actionerror> tag is given in the form.