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.


Post Your Comment

Image

Enter the code given in the above image :
Enter Your Name :
Enter Your Email Address :
Enter Your Comment :

Comments


Posted By madhusudhan On 01-Dec-09 07:04:22 AM

sir in this example, in struts.xml under register action, you have specified the result "input". but in the actionclass, the execute method is not returning the "input" rather it is having the success.. plz explain me sir..



Posted By Srikanth Pragada On 01-Dec-09 02:39:20 PM

input string in action configuration specifies the page to be displayed if any validation errors occur. So in the example, if execute() method returns success it goes to registered.jsp, if any validation occurs it goes to register.jsp.



Posted By srinivasu namburi On 02-Dec-09 09:59:01 AM

I came to understand from above topic is, validations in struts 2.0 is bit simpler when compared to 1.x version and no need to add extra plugins as like in 1.x version.Thx for the example.



Posted By jay On 21-Jan-10 12:24:18 PM

Superb!!! I m new to struts 2.0! I know to give validation without using validate() function...Thanks a lot



Posted By Raaz Nagulapalli On 03-Mar-10 10:28:43 PM

sir i am one of the regular visitor of your website for learning and updating my knowledge in java and j2ee applications. The stuff you are provided for visitor's is really good and useful to us.



Posted By ganesh On 14-Jun-10 04:11:44 PM

Am gettin the error struts-tags not found.Do i have to copy this from somewhere .if so from i can get it n to where i ve to copy that.



Posted By radhika On 08-Sep-10 03:53:28 PM

Hi i seem to have some problem here. The password and confirm password equality message is not getting displayed. I have added actionerror tag in the jsp. Please let me know where am i going wrong



Posted By Venkat On 18-Feb-11 03:23:59 PM

could you please us an example for password and confirm password matching. If two password do not match , it should us error message.

Thank you.



Posted By praveenkumar On 18-Jul-11 06:16:42 PM

dis is praveen new to struts
i m unable to use :::
import com.opensymphony.xwork2.ActionSupport;
can u pls suggest me how i can use xwork



Posted By Durga On 19-Mar-12 03:11:39 PM

The above example is very simple and easy to understand tnq.



Posted By deepak On 01-May-12 02:50:27 PM

I am using netbeans so where to put this registeraction-validation.xml file in directory .



Posted By ram On 14-May-13 10:17:30 AM

thanks for your example.i am done validations according to my program using struts2 but i am getting exceptions like there is no name space for action.
but i am providing result tag for both input and success.but in my jsp im using normal form.is there any problem with out using struts2 from.thanks in advance....



Posted By Ashwanth On 10-Oct-13 09:30:04 AM

It is good example for the beginners