Struts2 Validation Framework Tutorial with Example

struts2-validation-framework
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.

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>

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.
customer-action-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).
struts2-validation-jsp-files
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.
struts2-customer-form

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.
struts2-validation-xml
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
struts2-customer-form
Customer page with errors
customer-page-validation-errors
Customer page on success
customer-page-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.



104 Comments

  • crazzy coder 3 December, 2012, 23:04

    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()&lt;10)
            {
                addFieldError(&quot;mobile&quot;,&quot;Mobile Must Be Of 10 Digits&quot;);
            }
                 if(user.getLandline()==0)
            {
                addFieldError(&quot;landline&quot;,&quot;Please Enter The Landline Number&quot;);
            }
                 if(user.getEmail().length()==0)
            {
                         if(user.getSecurityquestion().length()==0)
            {
                addFieldError(&quot;securityquestion&quot;,&quot;Please Enter A Security Question&quot;);
            }
                   if(user.getAnswer().length()==0)
            {
                addFieldError(&quot;answer&quot;,&quot;Please Enter The Answer&quot;);
            }
                 
            }
        }
    }
    
    • Akhilesh 3 May, 2013, 11:49

      Thanks, that’ s really a elegant approach. Sounds similar spring mvc

    • Alkaram Ansari 5 August, 2013, 18:43

      perfect code.
      tested this code in eclipse indigo, apache7, struts2.
      successfully running.
      thanx

  • Manikandan 20 December, 2012, 16:42

    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…

    • Niraj 16 January, 2013, 0:42

      Hey!
      i think your some of your Jsp pages are containing error.!
      Also,make sure you have all libraries in your project.!

  • rj4u 27 December, 2012, 17:38

    I am getting the same error as Manikandan. I get the error only when I add the validate = “true” in the jsp. Please help!

  • rj4u 27 December, 2012, 17:46

    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.

    • adolf 15 February, 2013, 14:17

      Hi rj4u, how did you fixed you error, i meet the same one.

      • Gagan 19 June, 2014, 19:59

        I am also getting the same error, please forward you fixed that error.

  • xcoder 27 December, 2012, 18:15

    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)

  • crocosaurus 15 January, 2013, 15:30

    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!

  • Kleus 16 January, 2013, 11:22

    Hi I follow your steps but it seems like the validator is not working.
    Thanks in advance for replying.

  • Robin 28 January, 2013, 1:36

    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

  • Janu 13 February, 2013, 15:37

    I am trying to add struts 2 validations in struts 2+spring+hibernate application … but it is not getting effected can you help me

  • adolf 15 February, 2013, 14:15

    Same error as rj4u,

    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@4028a3 - Class: freemarker.ext.beans.SimpleMethodModel
    File: SimpleMethodModel.java
    Method: exec
    Line: 130 - freemarker/ext/beans/SimpleMethodModel.java:130:-1
     

    I am using freemarker-2.3.19.jar , struts2-core-2.3.4.1.jar, xwork-core-2.3.4.1.jar

    • AK47 30 April, 2013, 9:45

      @RjforU,Adolf
      Download the project folder shared by them.Replace your lib files with their lib files.It will work.

  • Paarul 20 February, 2013, 0:52

    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

  • Ryan 25 March, 2013, 8:49

    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

  • Oddidodd 20 April, 2013, 16:49

    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">
    
  • Kshama Joshi 16 May, 2013, 12:05

    Heloo.. I am a novice here…
    pls help me with the following error

    SEVERE: Caught exception while loading file net/viralpatel/struts2/CustomerAction-validation.xml
    Connection refused: connect - [unknown location]
    	at com.opensymphony.xwork2.util.DomHelper.parse(DomHelper.java:115)
    	at com.opensymphony.xwork2.validator.DefaultValidatorFileParser.parseActionValidatorConfigs(DefaultValidatorFileParser.java:69)
    	at com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.loadFile(AnnotationActionValidatorManager.java:338)
    	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    	at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    	at java.lang.Thread.run(Thread.java:619)
    Caused by: java.net.ConnectException: Connection refused: connect
    	at java.net.PlainSocketImpl.socketConnect(Native Method)
    	at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    	at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    	at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    	at javax.xml.parsers.SAXParser.parse(SAXParser.java:395)
    	at com.opensymphony.xwork2.util.DomHelper.parse(DomHelper.java:113)
    	... 63 more
    
    • Fabian 25 August, 2013, 17:47

      Hey Kshama Joshi,

      i’ve got the same error like:

      "SEVERE: Caught exception while loading file net/viralpatel/struts2/CustomerAction-validation.xml"
      

      solved it by changeing the .dtd transcription in the -validation.xml Doctype to:

      <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
      

      the Open Symphony “xwork-validator.dtd” wasn’t available in the Framework i’ve loaded. so changing the Doctype to the one mentioned above should solve your problem.
      Best Regards Fabi

      • Fabian 25 August, 2013, 17:49

        sorry the code snippet changed my Doctype:
        i mean you have to add:

        BR Fabi

  • Faizal 28 May, 2013, 11:15

    @rj4u and Adolf ,,Just add aappend(.action) to your attribute tag of ur JSP file like

  • Dipen 31 May, 2013, 11:50

    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.

  • Snigdha Batra 11 June, 2013, 13:58

    Good tutorial!!

  • Manish Kumar 12 June, 2013, 14:25

    I have several runtime error in ecllipse in my struts 2 SImple Login Form. Pl see my errors

    Jun 12, 2013 2:24:03 PM com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    INFO: Loading global messages from resources
    Jun 12, 2013 2:24:04 PM com.opensymphony.xwork2.util.logging.commons.CommonsLogger error
    SEVERE: Dispatcher initialization failed
    Unable to load configuration. - action - file:/E:/testservlet/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/struts2Login/WEB-INF/classes/struts.xml:8:58
    	at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:69)
    	at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:390)
    	
    	at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
    Caused by: Action class [com.struts2.LoginAction] not found - action - file:/E:/testservlet/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/struts2Login/WEB-INF/classes/struts.xml:8:58
    	at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.verifyAction(XmlConfigurationProvider.java:426)
    	at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addAction(XmlConfigurationProvider.java:370)
    	at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:487)
    	at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:278)
    	at org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:112)
    	at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:204)
    	at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:66)
    	... 22 more
    Jun 12, 2013 2:24:04 PM org.apache.catalina.core.StandardContext filterStart
    SEVERE: Exception starting filter struts2
    Unable to load configuration. - action - file:/E:/testservlet/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/struts2Login/WEB-INF/classes/struts.xml:8:58
    	at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:449)
    	at org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:69)
    	at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:51)
    	at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:295)
    	
    	at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
    Caused by: Unable to load configuration. - action - file:/E:/testservlet/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/struts2Login/WEB-INF/classes/struts.xml:8:58
    	at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:69)
    	at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:390)
    	at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:436)
    	... 20 more
    Caused by: Action class [com.struts2.LoginAction] not found - action - file:/E:/testservlet/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/struts2Login/WEB-INF/classes/struts.xml:8:58
    	at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.verifyAction(XmlConfigurationProvider.java:426)
    	at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addAction(XmlConfigurationProvider.java:370)
    	at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:487)
    	at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:278)
    
    • Manjusha 4 September, 2013, 12:53

      Hi,
      You dont have all libraries needed in your lib folder.Check it once.

  • Sushant 24 June, 2013, 12:08

    Hey i want to know what can i use the datatype for grouping the variable,plz any one know this tell me….im trying to develop the web site blog i have completed 60% but i dont have idea about how can i gruop the reply variable which is automatically increament as per replys will increament…Plz help me in this…

  • Soumi 3 August, 2013, 9:25

    Thanks…. all your struts related tutorials are very mush useful as well as helpful..

  • sunil 12 August, 2013, 0:22

    Hey really a nice example….
    but i am facing one problem where will i get the ApplicationResources.properties file in netbeans 7.1
    i am getting the output but validations are not getting performed.please help me.
    thanks in advance

  • Milan 21 August, 2013, 16:32

    i have struts2-tiles-plugin-2.0.11.2.jar in lib,but when deploy gives this error in console:

    can help me?

    thanks

  • Milan 21 August, 2013, 16:33

    i have struts2-tiles-plugin-2.0.11.2.jar in lib,but when deploy gives this error in console:

    can help me?

    thanks

  • Milan 21 August, 2013, 16:34

    i have struts2-tiles-plugin-2.0.11.2.jar in lib,but when deploy gives this error in console:

    can help me?

    thanks

  • subba reddy venna 28 September, 2013, 18:38

    when i run application i get the following error !!!

    Sep 28, 2013 6:38:05 PM com.opensymphony.xwork2.util.logging.commons.CommonsLogger warn
    WARNING: No configuration found for the specified action: ‘Display’ in namespace: ”. Form action defaulting to ‘action’ attribute’s literal value.
    Sep 28, 2013 6:38:06 PM com.opensymphony.xwork2.util.logging.commons.CommonsLogger warn
    WARNING: No configuration found for the specified action: ‘Display’ in namespace: ”. Form action defaulting to ‘action’ attribute’s literal value.
    Sep 28, 2013 6:38:08 PM com.opensymphony.xwork2.util.logging.commons.CommonsLogger warn
    WARNING: Could not find action or result
    There is no Action mapped for namespace / and action name Display. – [unknown location]
    at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:189)
    at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
    at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
    at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:475)
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)

  • Mr.Chowdary 1 October, 2013, 19:30

    Article explaning with field level validations is quite impressive.
    But how to validate in case of index based form fields?
    Any Idea is highly appreciated.. :)

  • sudhakar 18 November, 2013, 15:51

    when i run application i get the following error !!!
    please help me.

    There is no Action mapped for namespace [/] and action name [Customer] associated with context path [/StrutsExample]. – [unknown location]
    at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:185)
    at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
    at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
    at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:553)
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Unknown Source)
    Nov 18, 2013 3:40:12 PM org.apache.struts2.dispatcher.Dispatcher error
    SEVERE: Exception occurred during processing request: There is no Action mapped for namespace [/] and action name [Customer] associated with context path [/StrutsExample].
    There is no Action mapped for namespace [/] and action name [Customer] associated with context path [/StrutsExample]. – [unknown location]
    at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:185)
    at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
    at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
    at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:553)
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Unknown Source)

  • satya 21 December, 2013, 13:35

    Hi Virat,
    Its nice tutorial, very help ful for beginners like me.
    I have tried as mentioned in the totorial for client side validation.
    But it is not working.

    Pls update how to implement validation when we are using beans.

    Thanks

  • Swapnil 3 February, 2014, 22:02

    How to Skip the validation from Submit Button

    • Amol 4 March, 2014, 13:01

      simply call the validation method in onblur event

  • Amol 4 March, 2014, 13:00

    how to add validation code in struts2

  • Adeline 15 March, 2014, 15:04

    Do you mind if I quote a couple of your articles as long as I provide
    credit and sources back to your blog? My
    blog site is in the exact same area of interest as yours and my users would truly benefit from a lot of the information you provide here.
    Please let me know if this okay with you. Cheers!

  • Raja 22 March, 2014, 14:48

    Struts2 validation is not working when if you use tag and if you display both the result and the UI form in same jsp .. why?

  • kaushal jani 9 April, 2014, 18:31

    I am working with struts2 and with json.
    my client side is on android and when user/client send request in url it should check server validation and store in database and should only return required fields with status and set message.

  • Ramakrishna K.C 28 April, 2014, 16:04

    I dint get validate=”true” in customer.jsp. What kind of javascript validation code is added by struts-2? Please explain..

    Thanks:
    Ramakrishna k.c

  • Bhupesh Upadhyay 3 August, 2014, 22:05

    from where we have to open -validation.xml in netbeans7.0

  • Asmita 4 August, 2014, 14:58

    Hi

    when i put Validate =”true” in JSP i am facing error ,but without validate=”true”it is working fine

  • Kamruddin Ali 21 September, 2014, 13:37

    Many thanks for the great tutorial. You mentioned to add validate=”true” in form tag to enable javascript validation. It is working fine. But one thing i noticed is that for the very first time (when you click Add Customer button ) , validation is server-side, but after that validation is client side. Do you see that too?

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current ye@r *