Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Struts2 Validation Framework

In this article we will talk about validation using the Struts2 Framework. We will also learn about Validation Interceptor and how we can implement it on a default stack.

Struts2 Framework has provided many enhanced features, while comparing to earlier versions of the Struts. Validation Framework, which is newly introduced in the Struts2, provides client and server types of validations. It’s very much maintainable and provides robust process for handling the validations.

It has some built-in validators which we can directly use to validate the form likeemailvalidation andrequiredstring.

Struts2 Validation Framework has come up in an innovative way in terms of modularity, integration and architecture.

How it works?

Flow Diagram

Figure 1: Flow Diagram

Actions class works as a domain data and it looks for the properties in its Action Mapping File and it searches the field validators in theFileName-Validation.xmland all validators work as per the field defined in validation.xml. If there is any mismatching of data, it picks the message from the validation.xml and displays it to user.

Role of Validation Interceptor

The validation interceptor basically provides entry into the validation framework. We can define the Validation interceptor in the default stack which provides you an entry point validation Process.

<interceptor-ref name=”validation/>

Validation interceptor runs the action through the standard validation framework. It basically checks the action against the defined validation rules and basically adds the field level and action-level error.

Working with Validations in Struts 2

Now, we will understand how we can use the Validation Framework to define our own validators.

UsingRegisterAction

The earlier version of Struts used theRegisteraction to validate the data. The execute method of the Register action just creates an object with the submitted data and persists that particular object.

Define your own Validators

We define our own validators in-validation.xml. Validators could be of different- types. Struts2 also provides many built-in validators to perform the validation. Instead of writing validation part in validate() method, here we had put out validation in a metadata XML File which contains the preferred logic of the validation.

Field and non Field Validators

Field validators are individual validators with no parameter values.

Non-field validators allow you to define both type of validators field-validators as well as non-field validators. Non-field validators apply the whole action and it contains constraints that could include one of more field value, we can perform the validations like comparing or checking the range type of validations. We can define our custom logic by using non-field validators.

Field Validator


<field-validator type="requiredstring">
<message key="user.error.required" />
</field-validator>


field-validator can be simply declared with

Non - Field Validator


<field-validator type="int">
<param name="min">5000</param>
<param name="max">200000</param>
<message key="Your Credit Card limit is range from ${min} and ${max}!"/>
</field-validator>

Non-field validators add the action level of messages or they are basically domain specific.

Message Element Options in Validators

We used themessageelement to define the message that gets displayed to the user as a validation error on the Page. We define the messages on each validator declaration. If validation fails, the message will be displayed on browser.

We can define the messages in 2 ways:

Message inside Configuration file:

<field-validator type="requiredstring">
<message key="First Name cannot be left blank"/>
</field-validator>

You can directly write the message inside the validator configuration file.

Define your messages in property file:

<field-validator type="requiredstring">
<message key="validation.fname”/>
</field-validator>

Another way of displaying the message from ApplicationResource.properties

  • Property file: ApplicationResource.properties
  • Validation.fname=First Name cannot be left blank

Note: ApplicationResources.properties must be at the class-path of your project, either in resources folder or any folder at your class-path. 

In-Built Validators – Struts 2

Struts2 provides various types of built-in validators, which are commonly used in almost every web application. We can use them directly in validation.xml.

Name of ValidatorParameter ValuesDescription
required

trim, by default its true

It trims the whitespace

It checks whether the value is null or not.
requiredstring

trim, by default its true

It trims the whitespace

It checks whether the value is null or not.
stringlengthtrim,(its default value is true and it trims based on length), minLength, maxLengthIt verifies the string length between the min and max value.
intmin,maxVerifies the integer value between the specified ranges.
double

minInclusive

maxinclusive

minExclusive

maxExclusive

Verifies the double value between the specified ranges.
datemin,maxVerifies the date value between the specified ranges. You should specify the date in MM/DD/YYYY format.
emailNoneVerifies the Email Address format
urlNoneVerifies the URL Format
fieldexpressionexpressionIt basically evaluates an OGNL expression against the value in current Value Stack. Expression return type must be true or false for the determination of true or false.
expressionexpressionUsed at action level.
visitorContext, appendPrefixValidates the domain object property.
regexExpression (must appear) caseSensitive, trimMatch the input string against the patterns specified in param expression.

Customized Validators

Apart from the built-in validators provided by Struts2, we can define our own Validator and use them in Validation.xml.

Define your own Customize Validator

In addition to built-in validators, we can define our own custom validators. We can define our own class and configure in validators.xml and you can use the validators likewise we used in-built.

Here, we have defined one CustomEmailValidator, which checks the email-id format and validates it, that whether the email-id ends withmrbool.comor not.

Listing 1: CustomEmailValidator

package com.mrbool.validators;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
public class CustomEmailValidator extends FieldValidatorSupport  {
    private String emailRegex;
    public String getEmailRegex() {
        return emailRegex;
    }
    public void setEmailRegex(String emailRegex) {
        this.emailRegex = emailRegex;
    }
    @Override
    public void validate(Object obj) throws ValidationException {
        String email=getFieldName();
        String emailVal = (String)getFieldValue(email, obj);
        if(!emailVal.endsWith("mrbool.com")){
            addFieldError(email, obj);
        }
    }
}

FieldValidatorSupport validator provides a Validation supporting facilities in your class. This class provides the services to help in validation. You can write your validation part in Overridden validate (Object o) method. addFieldError adds the error sent by myAction-validation.xml

Configure your Validator

Once, you have constructed your Validator, your next task is to configure that validator inValidators.xml.

Listing 2:Validators.xml

<!DOCTYPE validators PUBLIC
  "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
  "http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
<validators>
<validator name="customeemail" class="com.mrbool.validators.CustomEmailValidator"/>
</validators>

Create a file namedValidators.xmlunder thesrcor at the classpath of the Project and define your validator name and class location. This exercise will register your own custom validator in the Validation framework.myAction-Validation.xmlwill initially load custom validators first in its dictionary and then you can use your validators normally as you've used in-built one.

Using Custom Validator

After configuration phase, we can all the custom validator in myAction-validation.xml.

Listing 3: myAction-validation.xml

<Validators>
<field name="email">
    <field-validator type="customeemail">
        <param name="emailRegex">mrbool.com</param>
        <message key="Your Email ID should end with mrbool.com"/>
    </field-validator>
    </field>
</validators>

Using field-validator element, we can utilize our customized validator in param attribute's name we've defined default format as mrbool.com, which indicates that my emailid must end with yourname@mrbool.com. In case of any other improper input, message will be displayed to the user.

Whatever the property name, you will pass in param name's value that property must exist in your Action class that is extending FieldValidatorSupport. Since, it will look for that property in your action class.

Validation Framework with Model Actions

Short Circuit Validations

Short Circuit validation gives a facility to short-circuit some part of validation instead of checking the rest of validators.

Listing 4: Short Circuit Validations


<field name="name">

   <field-validator type="int" short-circuit="false">

    <param name="min">1</param>

    <param name="max">100</param>

    <message key="First name cannot be more than 6 characters"/>

   </field-validator>   

   <field-validator type="regex">

     <param name="expression">^[a-zA-Z'][a-zA-Z' ]*[a-zA-Z']?$</param>

     <message key="user.error.text"/>

   </field-validator>

</field>

Suppose, you have several set of validations for one field that is validating the first name cannot be more than six characters and then other is checking that first name cannot contain numbers. If your first name is not more than 6 characters then still it will perform the next validation for the number in field. So, there is no point of wasting the time and checking for every validation on a single field. If first validation fails than that validation will be displayed to the user rest of the validations will short-circuited.

Validation with Annotation

We can define the set of validations in the class file itself using the validation annotations provided by Struts Framework.

@RequiredStringValidator(type=ValidatorType.FIELD,
 message="Name cannot be left blank")
    public String getName() {
        return name;
    }

ValidatorType.FIELD gives you the same functionality, which

@Validations()
public class UserRegistrationAnnotated extends ActionSupport
{    ...

To avail the validation feature in our own customized class then you have to annotate your class by@validationsannotation, that will enable validations for your class and you can use all built-in Validations as what you've used withinyourAction -validations.xml.

User Validation - By an Example

A Web-form performs the basic validation of the User Name, Age and Email-ID. A Web-form is created with said elements and comprised in the web-form.

Listing 5: User Validation Example

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="cj" uri="/struts-tags"%>
<html>
<head>
<title>User Registration : mrbool.com</title>
<link href="css/layout.css" rel="stylesheet" type="text/css">
</head>
<body>
<center>
<h2 class="heading">User Registration</h2>
<cj:form action="customer" method="post" validate="true" theme="xhtml">
    <cj:textfield name="name" key="name"/>
    <cj:textfield name="age" key="age"/>
    <cj:textfield name="email" key="email"/>
    <cj:submit method="addUser" key="user.submit" align="center" />
</cj:form>
</center>
</body>
</html>

Essential declaration to create a Struts-enable page is to declare the <%@ taglib prefix="cj" uri="/struts-tags"%> element on the top of the form and the css is imported in the page just for the positioning of the elements.

Then when the page is submitted, it will look for the addUser() method in the respective Action class to perform the validation step based on the configuration done in struts.xml.

Listing 6: Layout.css

.heading{font-family: arial;color:#800000;}
.bStyle{font-family:arial;}

Listing 7: Struts Configuration file (struts.xml)

<?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="ApplicationResources" />
    <package name="default" extends="struts-default" namespace="/">
        <action name="customer"
            class="com.mrbool.validation.example.UserRegistration">
            <result name="success">Welcome.jsp</result>
            <result name="input">UserRegistration.jsp</result>
        </action>
    </package>
</struts>

If you have security concerns, or would like to use the "!" character with Wildcard Method actions, then set struts.enable.DynamicMethodInvocation to FALSE in the application configuration. Package name is type of “default”. It defines the default result types, interceptors and some other defaults. If you don’t declare the package type default then you need to do some work around in your own package.

An Action is declared with named “customer” who redirects the control to the ActionForm UserRegistration declared in the com.mrbool.validation.example package to perform the desired validation.

Action Form configured in the struts.xml with the method addUser() and here the method addUser() is declared with just the SUCCESS as return type and along with UserRegistration there must be a validation with the same name followed by hypen(‘-‘) and validation.xml.

If your Action class is named as UserRegistration and the same name xml file must be there in the same package where the Action class is lying with UserRegistration-validation.xml. This Validation xml file allows the container to look into the Validation file first and check all the validation declared in the xml file.

Listing 8:UserRegistration-validation.xml

package com.mrbool.validation.example;
import com.opensymphony.xwork2.ActionSupport;
public class UserRegistration extends ActionSupport{
    private String name;
    private Integer age;
    private String email;
    public String addUser() {
        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;
    }
}


UserRegistration-validation.xml

The validation can be performed in either two ways, one is using the XML file and the other way is to annotate your validation within the UserRegistration.java(Action class).

Please note that in case of the Xml Validation, a xml file gets created just parallel to the your Action class(UserRegistration.java) and the file must be named as: -validation.xml or also the alias can be given as --validation.xml

Listing 9: Action Class Name

<!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">            

            <message key="user.error.required" />

        </field-validator>

         <field-validator type="regex">

          <param name="expression">^[a-zA-Z'][a-zA-Z' ]*[a-zA-Z']?$</param>

          <message key="user.error.text"/>

         </field-validator>

    </field>

    <field name="age">

        <field-validator type="required">

            <message key="user.error.required" />

        </field-validator>

        <field-validator type="int">

            <param name="min">1</param>

            <param name="max">100</param>

            <message key="${getText(fieldName)} must be in range of ${min} and ${max}"/>

        </field-validator>

    </field>

    <field name="email">

        <field-validator type="requiredstring">

            <message key="user.error.required" />

        </field-validator>

        <field-validator type="email">

            <message key="user.error.invalid" />

        </field-validator>

    </field>    

</validators>

An example has been given here, shows the validation has been performed for the user that it should only be alphabetical and for age it must be from 1 to 100 and moreover, the last email validation has been performed that the input must match a valid email pattern.

Validation using the Annotation

This is the second type of the validation, rather than performing the validation in the xml file as you’ve seen earlier; it can also be performed in the Action class itself.

Listing 10: Validation with Annotation

package com.mrbool.user.action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.*;
public class UserRegistrationAction extends ActionSupport {
    private String username;
    private String password;
    private int age;
    public void setAge(int age){
        this.age = age;
    }
    @RequiredFieldValidator(message="Age cannot be left blank.")    
    @IntRangeFieldValidator(min = "0", max="30", message="The age must be beetween ${min} to ${max}")
    public int getAge(){
        return this.age;
    }
    @RequiredStringValidator(message = "User name cannot be left blank.")
    public String getUsername() {
        return username;
    }
    public void setUsername(String value) {
        username = value;
    }
    @RequiredStringValidator(message = "Password cannot be left blank.")
    public String getPassword() {
        return password;
    }
    public void setPassword(String value) {
        password = value;
    }
    public String execute() throws Exception {
            return SUCCESS;
    }
}


Listing 11: Configuration needed in the struts.xml for the annotation validation

<?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="ApplicationResources" />
    <package name="default" extends="struts-default" namespace="/">
        <action name="UserRegAction" class="com.mrbool.user.action.UserRegistrationAction">
            <result name="input">login.jsp</result>            
            <result>home.jsp</result>
        </action>
    </package>
</struts>

Create your own Custom Validator

Apart from the validators are provided by the Struts 2, you can create your own Custom Validator, which can be used to validate the fields with your own type of validation. You need to extend your custom validator with FieldValidatorSupport to act your class as validator.

Listing 12: JSP Page

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="cj" uri="/struts-tags"%>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<div align="center">
    <b>Registration Form</b><br/><br/><br/>
    <cj:form action="UserRegActionWithCust" method="post" validate="true">
        <cj:textfield name="username" label="Login name" />
        <cj:password name="password" label="Password" />
        <cj:textfield name="age" label="Age" />
        <cj:submit method ="addUser" value="Register" align="center" />
    </cj:form>
    </div>    
    </body>
</html>

A web page has been created with username, password and age and we’re going to validate the password that the password must contain one special character, one digit(0-9) and one upper(A-Z) & lower case letter(a-z) and the length of the password must be 8-20.

The JSP Page looks for the action in the struts.xml with action name “UserRegActionWithCust” and the action class “com.mrbool.custom.validator.PasswordValidationAction” is configured against the action name “userRegActionWithCust” .

Listing 13: struts.xml

<action name="userRegActionWithCust" class="com.mrbool.custom.validator.PasswordValidationAction">
<result name="input">LoginWithCustVal.jsp</result>            
    <result>home.jsp</result>
</action>

PasswordValidationAction.java

In PasswordValidationAction.java we have defined an execute() method which container looks for when no method is provided in form. The SUCCESS annotation has been returned from the execute() but first the container looks for any file named -validation.xml before returning the SUCCESS and the PasswordValidationAction-validation is introduced at the same package where your action is lying.

Listing 14: Password Validation

package com.mrbool.custom.validator;
import com.opensymphony.xwork2.ActionSupport;
/**
 * Action file for the Password Validation.
 * @author mrbool
 */
public class PasswordValidationAction extends ActionSupport {
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String execute(){
        return SUCCESS;
    }
    private String username;
    private String password;
    private int age;
} 

PasswordValidationAction-validation.xml

In validation file, the custom password validator is configured which performs the actual validation related to the password.

Listing 15: Action Validation

<?xml version="1.0" encoding="UTF-8"?> 
 <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator Config 1.0//EN" 
 "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
    <field name="password">        
        <field-validator type="passwordValidator">            
            <message key="Your password must contain One Upper case letter, Special character and a digit."/>
        </field-validator>
    </field>
</validators>


NOTE: Please note that a file name with validators.xml must exists at the class path of your project because the container looks for class in validators.xml against the name passwordValidator.

Here is the configuration of the validators.xml

Listing 16: validators.xml configuration

<!DOCTYPE validators PUBLIC   
  "-//OpenSymphony Group//XWork Validator 1.0.2//EN"  
  "http://struts.apache.org/dtds/xwork-validator-definition-1.0.dtd">  
<validators>
    <validator name="passwordValidator" 
    class="com.mrbool.custom.validator.PasswordValidator" />
</validators>

The class PasswordValidator is a custom validator, which is defined in validators.xml. So, container checks for the password validation in PasswordValidator class.

Listing 17: PasswordValidator.java

package com.mrbool.custom.validator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
/**
 * This class is a custom Validator for performing the password validator.
 * Your password should contain:
 * 1. A special character(@#$%)
 * 2. A Lower Case character(a-z)
 * 3. A digit(0-9)
 * 4. A Upper case character(A-Z)
 *
 * @author mrbool
 * 
 */
public class PasswordValidator extends FieldValidatorSupport {
    private String password;
    private String age;
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getPassword() {
        return this.password;
    }
    @Override
    public void validate(Object object) throws ValidationException {
        String fieldName = getFieldName();
        Object value = this.getFieldValue(fieldName, object);
        String s = (String) value;
        if(!isPasswordValid(s)){
            addFieldError(fieldName, object);
        }
    }
    private boolean isPasswordValid(String password){
        Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20})");
        Matcher m = p.matcher(password);
        return m.matches();        
    }
}

FieldValidatorSupport is a base class for all field validators. By default the validate() method will get called up in order to perform the validator and using the regular expression, we have validated the password if the password followed what is written in class doc then the success will get called up from PasswordValidatorAction. And if password does follow the basic requirements then we have added field error to the page. Whatever the message is written in the PasswordValidationAction-validation.xml against the password field in the

In this article, we learnt some basic validation using the Struts2 Framework. We talked about Validation Interceptorand how we can implement it on a default stack.

What is the role ofRegisteraction in action class? we went through the built-infieldas well asnon fieldValidators.FieldValidators works on a single individual field whereasnon-fieldvalidator applies on the whole action and it contains constraints that could include one of more fields.

We can define validation message inAction-Validation.xmlin two ways: from property file or other defined your message in XML file itself.

You were shown some built-in validators, which are provided by Struts2 Framework. We can create our own Custom Validators and use in the same manner as we used built-in validator and how to configure your own validator in Validators.xml.

We can use short-circuit validation to break the validation into parts and how to use the Validation with annotations in the class itself.

We have studied about the custom validators and how we can create our own custom validators and perform the validation with them.



I love to code and analytics. Interested in designing creative things which can be really helpful to the peoples.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login