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>
<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)
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). <%@ 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. 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.Code language: HTML, XML (xml)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}.
<!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. <s:form action="customer.action" method="post" validate="true">
...
</s:form>
Code language: HTML, XML (xml)
Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…
Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…
Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…
1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…
GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…
1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…
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
It is a really great tutorial..Couldn't thank you enough.
thanks !tutorial are very good!
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..