× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


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

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

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


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

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

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

How to create a Struts Validation in Java

In this article we will talk about Validation in Struts Framework.

It is important that only valid data enters the data store. Any application that does not meet this basic requirement will not be useful in a real situation. Attempts to insert, update or access data without valid input should be interrupted before accessing the data layer. For example, a user entering an invalid combination of user name and password should be stopped before getting into the application. This basic validation ensures that the system is secure. However, this need for validation sometimes becomes redundant, in that the same validation is performed in many places, over and over again. This repetition/ duplication of validation means increased effort in maintaining the code. It also increases the development and defect fixing time. It can create unnecessary confusion and sometime negative impacts on the code. A better way is to keep the validation at just one layer. Keeping the validation code to just one layer translates to lower cost and time. This also ensures that code is easier to read and manage.

There are two ways to do validation in struts - one is to use the validate () method and the other is to use the struts validator framework. This tutorial deals with using the ActionFormvalidate() method to validate the ActionForm bean properties. It is one of the simplest validation methods available with Struts.

ActionFormvalidate() Method

The validate method in the Struts Action form provides for a simple yet elegant way to validate the Struts ActionForm properties. The method is invoked before executing the ActionForm and any errors encountered while executing the validate method are returned as collection of error messages. ActionErrors type acts as the collection and ActionMessage act as the error messages that are added to the collection, ActionErrors. One or more properties in a Form class can be validated and all the error messages can be added to a single collection. The error messages are message keys of the message resource bundle that is registered with the struts-config.xml. The validation is performed during the process validation lifecycle phase. If there are validation errors, the life cycle skips all the subsequent phases and reaches the render response phase, during which the error messages are displayed in the same screen.

This sample application is an extension of the Struts login application. Here, the validate method is used to perform validation of ActionForm properties.

Listing 1: UserInformationForm.java

public class UserInformationForm extends ActionForm {
	private static final long serialVersionUID = 1L;
	private String username;
	private String password;
	public String getUsername() {
		return username;
	public void setUsername(String username) {
		this.username = username;
	public String getPassword() {
		return password;
	public void setPassword(String password) {
		this.password = password;
	publicActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		ActionErrors errors = new ActionErrors();

		//validate the username property of the form bean
		if (getUsername() == null || ("".equals(getUsername()))) {
			errors.add("username", new ActionMessage(
               // validate the password property of the form bean
		if (getPassword() == null || ("".equals(getPassword()))) {
			errors.add("password", new ActionMessage(
		return errors;

The code above shows the validate() method within the ActionForm. The validate() method checks the value for the username and password properties to see if they are empty. If they are empty, ActionMessages are created with corresponding error messages and added to the ActionErrors collection. The ActionErrors collection becomes the return value for the method. The ActionForm also contains the usual getter and setter methods for the username and password properties.

Listing 2: MessageResources.properties

error.no.userId=<li>User ID is a required field</li>
error.no.passWord=<li>Password is a required field</li>
error.invalid.login=<li>The User ID and/or Password are invalid. Please try again.</li>

The MessageResources.properties serves as the resource bundle for the application. The file is stored under the package com.src.prop. The resource bundle can have any number of messages. The first two messages in the bundle are the messages used in the validate method.

Listing 3: struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 

			<!--<form-bean name="userInformationForm"   
<form-property name="username" type="java.lang.String"/>
<form-property name="password" type="java.lang.String"/>
		<action scope="request"
			path="/Login" validate="true"
			name="userInformationForm" input="/pages/login.jsp"
			<forward name="success" path="/pages/welcome.jsp"/>
			<forward name="failure" path="/pages/login.jsp"/>
	<message-resources parameter="com.src.prop.MessageResources" null="false" />

The struts-config.xml includes some minor changes to enable the validation. The first change is to set validate=”true” in the Action class configuration. This enables the form bean validation. The second change is configuring the resource bundle.

<message-resources parameter="com.src.prop.MessageResources" null="false" />

The above line configures the resource bundle to be used for setting the error messages.


The login.jsp should display the error messages if form bean validation fails. Here’s is the contents of the login.jsp file.

Listing 4: login.jsp

<%@tagliburi="http://struts.apache.org/tags-html" prefix="html"%>
<%@tagliburi="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ tagliburi="http://struts.apache.org/tags-logic" prefix="logic" %>
<script type="text/javascript">
function login(){
document.forms[0].action = "Login.do?method=loginUser";

<h1>Struts Login Application</h1>
<html:form action="Login" >
<div style="padding:16px">
<html:errors property="username"/>
<html:errors property="password"/>
<div style="padding:16px">
	User Name
	<html:text property="username" size="20" maxlength="20"/>
	<html:password property="password" size="20" maxlength="20" />
<div style="padding:16px">
	<div style="float:left;padding-right:8px;">
		<html:submitonclick="javascript:login();" value="LOGIN"></html:submit>

The code above is similar to the previous example, except for the following two lines.

<html:errors property="username"/>
<html:errors property="password"/>

The first line displays the errors for the username field and the second line displays the errors for the password field.


The action class undergoes some changes too.

Listing 5: UserAction.java





public class UserAction extends Action{
	publicActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// TODO Auto-generated method stub

The Action class does nothing other than forwarding the request to the URL “success” which is configured to point to "/pages/welcome.jsp". This URL is reached only when all the validations succeed in the ActionForm. No validation code is included in the Action class as all the validations have moved to the ActionForm’s validate() method. Thus, the Action class method has become much simpler and easy to manage.

Listing 6: web.xml

 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<display-name>Struts Examples</display-name>

The web.xml did not undergo any changes. The web.xml configures the welcome page as login.jsp and includes the ActionServlet configurations as usual.

Running the application

Ensure that the build path has all the required jar files configured. Run the application on the server. Without entering the username and password fields, click the login button.

Running the application

Figure 1: Running the application

The validation error messages should appear on the screen if fields are left blank. If the fields have data, the click of login button should take the user to the welcome.jsp page.

This is all for today’s article. See you next time.

My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

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

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

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

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

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

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

Click here to login