Struts2 Validation Framework Tutorial with Example
- By Viral Patel on December 24, 2009

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.
Struts 2 Tutorials
- Part 1: Introduction to Struts 2
- Part 2: Create Hello World Application in Struts 2
- Part 3: Struts 2 Validation Framework Tutorial with Example
- Part 4: Struts 2 Tiles Plugin Tutorial with Example
- Part 5: Struts 2 Interceptors Tutorial with Example
- Part 6: Struts 2 File Upload and Save Example
- Part 7: Struts 2 Ajax Tutorial 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 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.
- Field Validators
- 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>
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;
}
}
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>
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>
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>
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>
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}.
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:
- Name field is mandatory
- Age field is mandatory. It should be a number between 1 and 100.
- 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 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>
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>
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.
Get our Articles via Email. Enter your email address.
you can alse use the inbuilt method of class ActionSupport
public String validate()
here is the example of it
//-------------EXAMPLE------------------ public class Adduser extends ActionSupport implements ModelDriven { User user=new User(); @Override public User getModel() { return user; } @Override public String execute() throws Exception { boolean flag=user.addUser(user); if(flag) return SUCCESS; else return ERROR; } @Override public void validate() { if(user.getUsername().length()==0) { addFieldError("username","Username Is Required"); } if(user.getPassword().length()==0) { addFieldError("password","Password Is Required"); } if(user.getName().length()==0) { addFieldError("name","Name Is Required"); } if(user.getDob().length()==0) { addFieldError("dob","Date Of Birth Is Required"); } if(user.getState().length()==0) { addFieldError("state","State Is Rquired"); } if(user.getCity().length()==0) { addFieldError("city","City Is Required"); } if(user.getMobile()<10) { addFieldError("mobile","Mobile Must Be Of 10 Digits"); } if(user.getLandline()==0) { addFieldError("landline","Please Enter The Landline Number"); } if(user.getEmail().length()==0) { if(user.getSecurityquestion().length()==0) { addFieldError("securityquestion","Please Enter A Security Question"); } if(user.getAnswer().length()==0) { addFieldError("answer","Please Enter The Answer"); } } } }Thanks, that’ s really a elegant approach. Sounds similar spring mvc
Hi i am following your steps. But when i submit the customer form it will sows the following error.
HTTP Status 500 –
——————————————————————————–
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
org.apache.struts2.impl.StrutsActionProxy.getErrorMessage(StrutsActionProxy.java:69)
com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:185)
org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:500)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:434)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.32 logs.
I don’t know? Why its come? And also how can i link the CustomerAction-validation.xml in this project? I am follows ur steps still i got the above error.
Help me…
Hey!
i think your some of your Jsp pages are containing error.!
Also,make sure you have all libraries in your project.!
I am getting the same error as Manikandan. I get the error only when I add the validate = “true” in the jsp. Please help!
More details of the error :
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: Method public java.util.List org.apache.struts2.components.Form.getValidators(java.lang.String) threw an exception when invoked on org.apache.struts2.components.Form@7309eabd – Class: freemarker.ext.beans.SimpleMethodModel
File: SimpleMethodModel.java
Method: exec
Line: 130 – freemarker/ext/beans/SimpleMethodModel.java:130:-1
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:570)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:457)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:88)
root cause
Method public java.util.List org.apache.struts2.components.Form.getValidators(java.lang.String) threw an exception when invoked on org.apache.struts2.components.Form@7309eabd – Class: freemarker.ext.beans.SimpleMethodModel
File: SimpleMethodModel.java
Method: exec
Line: 130 – freemarker/ext/beans/SimpleMethodModel.java:130:-1
org.apache.struts2.components.UIBean.end(UIBean.java:521)
org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
org.apache.jsp.Login_jsp._jspx_meth_s_005fform_005f0(Login_jsp.java:139)
org.apache.jsp.Login_jsp._jspService(Login_jsp.java:75)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:88)
root cause
freemarker.template.TemplateModelException: Method public java.util.List org.apache.struts2.components.Form.getValidators(java.lang.String) threw an exception when invoked on org.apache.struts2.components.Form@7309eabd
freemarker.ext.beans.SimpleMethodModel.exec(SimpleMethodModel.java:130)
freemarker.core.MethodCall._getAsTemplateModel(MethodCall.java:93)
freemarker.core.Expression.getAsTemplateModel(Expression.java:89)
freemarker.core.IteratorBlock.accept(IteratorBlock.java:94)
freemarker.core.Environment.visit(Environment.java:221)
freemarker.core.IteratorBlock$Context.runLoop(IteratorBlock.java:167)
freemarker.core.Environment.visit(Environment.java:428)
freemarker.core.IteratorBlock.accept(IteratorBlock.java:102)
freemarker.core.Environment.visit(Environment.java:221)
freemarker.core.MixedContent.accept(MixedContent.java:92)
freemarker.core.Environment.visit(Environment.java:221)
freemarker.core.ConditionalBlock.accept(ConditionalBlock.java:79)
freemarker.core.Environment.visit(Environment.java:221)
freemarker.core.MixedContent.accept(MixedContent.java:92)
freemarker.core.Environment.visit(Environment.java:221)
freemarker.core.Environment.include(Environment.java:1508)
freemarker.core.Include.accept(Include.java:169)
freemarker.core.Environment.visit(Environment.java:221)
freemarker.core.MixedContent.accept(MixedContent.java:92)
freemarker.core.Environment.visit(Environment.java:221)
freemarker.core.Environment.process(Environment.java:199)
freemarker.template.Template.process(Template.java:259)
org.apache.struts2.components.template.FreemarkerTemplateEngine.renderTemplate(FreemarkerTemplateEngine.java:157)
org.apache.struts2.components.UIBean.mergeTemplate(UIBean.java:565)
org.apache.struts2.components.UIBean.end(UIBean.java:519)
org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
org.apache.jsp.Login_jsp._jspx_meth_s_005fform_005f0(Login_jsp.java:139)
org.apache.jsp.Login_jsp._jspService(Login_jsp.java:75)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:88)
root cause
java.lang.NullPointerException
com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.buildValidatorKey(AnnotationActionValidatorManager.java:229)
com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.getValidators(AnnotationActionValidatorManager.java:86)
com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.getValidators(AnnotationActionValidatorManager.java:82)
org.apache.struts2.components.Form.getValidators(Form.java:265)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
freemarker.ext.beans.BeansWrapper.invokeMethod(BeansWrapper.java:866)
freemarker.ext.beans.SimpleMethodModel.exec(SimpleMethodModel.java:106)
freemarker.core.MethodCall._getAsTemplateModel(MethodCall.java:93)
freemarker.core.Expression.getAsTemplateModel(Expression.java:89)
freemarker.core.IteratorBlock.accept(IteratorBlock.java:94)
freemarker.core.Environment.visit(Environment.java:221)
freemarker.core.IteratorBlock$Context.runLoop(IteratorBlock.java:167)
freemarker.core.Environment.visit(Environment.java:428)
freemarker.core.IteratorBlock.accept(IteratorBlock.java:102)
freemarker.core.Environment.visit(Environment.java:221)
freemarker.core.MixedContent.accept(MixedContent.java:92)
freemarker.core.Environment.visit(Environment.java:221)
freemarker.core.ConditionalBlock.accept(ConditionalBlock.java:79)
freemarker.core.Environment.visit(Environment.java:221)
freemarker.core.MixedContent.accept(MixedContent.java:92)
freemarker.core.Environment.visit(Environment.java:221)
freemarker.core.Environment.include(Environment.java:1508)
freemarker.core.Include.accept(Include.java:169)
freemarker.core.Environment.visit(Environment.java:221)
freemarker.core.MixedContent.accept(MixedContent.java:92)
freemarker.core.Environment.visit(Environment.java:221)
freemarker.core.Environment.process(Environment.java:199)
freemarker.template.Template.process(Template.java:259)
org.apache.struts2.components.template.FreemarkerTemplateEngine.renderTemplate(FreemarkerTemplateEngine.java:157)
org.apache.struts2.components.UIBean.mergeTemplate(UIBean.java:565)
org.apache.struts2.components.UIBean.end(UIBean.java:519)
org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
org.apache.jsp.Login_jsp._jspx_meth_s_005fform_005f0(Login_jsp.java:139)
org.apache.jsp.Login_jsp._jspService(Login_jsp.java:75)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:88)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.12 logs.
Hi rj4u, how did you fixed you error, i meet the same one.
Hi..I followed the steps
But when i submitted the customer form it is throwing error in console and redirecting to success page.
Error:
SEVERE: Caught exception while loading file net/viralpatel/struts2/CustomerAction-validation.xml
Connection timed out: connect – [unknown location]
at com.opensymphony.xwork2.util.DomHelper.parse(DomHelper.java:123)
Hi,
if I had a validateCustomer method in my class, which validation method would be executed?
in other words, which validation method prevails: xml or programmatic validation
thanks!
Hi I follow your steps but it seems like the validator is not working.
Thanks in advance for replying.
customeraction-validation.xml and ApplicationResources.properties dont match the field and key/values. This is the reason u guys are getting errors when u run the program….
try to match the fields in both the “ApplicationResources.properties ” file and “CustomerAction-validation.xml” file then the program will work without any errors…….also there is an error in the ‘Form’ tag of “customer.jsp”……please change that to
once u make the above corrections your program will be error free……
good luck executing the program guys……….if u guys have issues with bugs u can mail me at RobinJohnson273@gmail.com……..please mention the name of the bug in the subject line…..im a java developer too…..im happy to help fresh minds who are eager to learn
I am trying to add struts 2 validations in struts 2+spring+hibernate application … but it is not getting effected can you help me
Same error as rj4u,
I am using freemarker-2.3.19.jar , struts2-core-2.3.4.1.jar, xwork-core-2.3.4.1.jar
@RjforU,Adolf
Download the project folder shared by them.Replace your lib files with their lib files.It will work.
Hi
My whole framework works well…I validates my form …redirect to form with error message when validation fails but ….when it redirect to the form after validation fail…I lose all my form data. I do not wish for user to re-enter information …I would like to retain all user input and let user update it…only thing I have done different is that I have not used key in the for I have separate label and name…Can you help me please ?
Thanks
error at struts 2 xml validation when using multiple validation per field. im using xwork-validator-1.0.3.dtd
You must enter a value for bar.
[/code xml]
Working fine with single field-validator though.
** also tried short-circuit still the same exception
I needed to add !DOCTYPE for my CustomerAction-validation.xml document. Great tutorial!!!
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">Heloo.. I am a novice here…
pls help me with the following error
@rj4u and Adolf ,,Just add aappend(.action) to your attribute tag of ur JSP file like
hey i have download ur example it works fine but when i try to build my own project everything works fine but client side validation is not performed. should i have to include some pacakges.
Good tutorial!!
I have several runtime error in ecllipse in my struts 2 SImple Login Form. Pl see my errors