Struts2 Validation Framework Tutorial with Example

Welcome to Part-3 of 7-part series of tutorials where we will go through different practical aspects of Struts2 Framework. In the last part we Created a Basic Struts2 Application from Scratch. I strongly recommend you to go through the previous articles in case you are new to Struts2. In this article we will learn how to leverage Struts2 Validation Framework in an application. For this we will use StrutsHelloWorld application which we created in previous article as base and starts adding validation logic to it. [sc:Struts2_Tutorials]

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 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.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>
Code language: HTML, XML (xml)
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>
Code language: HTML, XML (xml)

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. Copy following content into it. CustomerAction.java
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; } }
Code language: Java (java)
Note that CustomerAction class has fields name, email, telephone and age. Also it has a method called addCustomer() 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.
<action name="customer" class="net.viralpatel.struts2.CustomerAction"> <result name="success">SuccessCustomer.jsp</result> <result name="input">Customer.jsp</result> </action>
Code language: HTML, XML (xml)
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). Customer.jsp
<%@ 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>
Code language: HTML, XML (xml)
SuccessCustomer.jsp
<%@ 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>
Code language: HTML, XML (xml)
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.
<s:a href="Customer.jsp">Add Customer</s:a>
Code language: HTML, XML (xml)
Now open the ApplicationResources.properties file from /resources folder and add following key/values in it.
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}.
Code language: HTML, XML (xml)
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.

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. CustomerAction-validation.xml
<!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">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>
Code language: HTML, XML (xml)
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.
<s:form action="customer.action" method="post" validate="true"> ... </s:form>
Code language: HTML, XML (xml)

That’s All Folks

Execute the application and test the Customer form with different values. Customer page Customer page with errors Customer page on success

Download Source Code

Struts2_Validation_example.zip (3.6 MB)

Moving On

Now that we have implemented Struts2 Validation framework in our example, we know how exactly struts2 validation is handled. Also we know different types of validators like field-validators and non-field. In next part we will study Tiles framework and implement it in our application.

View Comments

  • Hi there,

    Great resource many thanks. Hey one thing I notice is that if I leave the Customer form empty and submit, then I get the following exception in the log;

    Caused by: java.lang.NoSuchMethodException: net.viralpatel.struts2.CustomerAction.setAge([Ljava.lang.String;)
    at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1206)

    Does Struts2 try and set the field as a String even though the type of it is int ?

    Cheers,
    Niall

    • Hi Niall,
      Thanks for pointing out the error. It seems there is some bug with the current version (There is JIRA ticket on this on Struts2 issue tracker - https://issues.apache.org/struts/browse/WW-2128).
      The problem is when we use generic type as attributes, ognl tries to set it as String. So here the workaround is to use wrapper classes (Int, Float) instead of generics (int, float).
      I am modifying the source code.
      Thanks again.

  • Hi Viral
    There is a error in the naming CustomerAction-validations.xml....if the name is changed to CustomerAction-validation.xml then only this example work properly else all fields are not validated by the framework .....i hope you will see that issue and post the reply ...

    Neways thanx for your nice and easy tutorials...
    Hope u will continue the same.

    • @karan - Thanks for pointing out the error. I have updated the tutorial. Although screenshot is showing correct name class.validation.xml. Thanks again.

  • Hii Viral ....
    you have rightly said that screen shots are showing the correct name .....i actually saw the corrections from the screen shots when my example was not working .......thanx for updating tutorial so fast .......it will help a lot to starters like me ..

    and how can we change the fonts or colors or alignments of our errror messages shown in this example...this question seems foolish ..but i dont mind bieng a fool ...lolzz

    and lastly could you please give a small tutorial on how to internationalize a webpage...actually i m trying this ..but getting some errors on output screen...if not then please post any gud link for all that in reply.....

    Thanx....

  • I like the way you write/explain the things.. I visit many pages, but the page you wrote are very good.

    Thanks, keep it up.

    ~VT

  • hi Viral,

    A ton thanks for your tutorial. Its working like a charm.

    If you can provide a bit more theory about how these validations actually works, it would be more helpfull.

    Any ways thanks for your work........Hoping to see lots of useful stuff from you.

    Regards,

    Jagadish

  • Hi, How do you implement validations with struts having a wildcard mapping? Because i seem to get an error

  • Thanks viral for the great work. You really simplified things. I was almost giving
    Up on struts until I found ur tutorial. Pls would be grateful if you could include
    Reading from an excel file and writing to an excel file using struts 2

  • Its amazing dear... THE BEST article of struts on entire web that i'v searched like hell.. The best part is you are providing all the required jars, tools and the source code of-course.. I am surely going to come back on your blog, for any kind of reference... keep it up buddy... you'll succeed..

Share
Published by
Viral Patel
Tags: Java Struts Struts 2 struts validator Struts2 struts2-series

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago