Struts 2 ActionError & ActionMessage Example

A tutorial to show the use of the Struts 2’s ActionError and ActionMessage class.

1. ActionError – is used to send error feedback message to user – display via <s:actionerror/>.


<s:if test="hasActionErrors()">
   <div class="errors">
      <s:actionerror/>
   </div>
</s:if>

2. ActionMessage – is used to send information feedback message to user, display via <s:actionmessage/>.


<s:if test="hasActionMessages()">
   <div class="welcome">
      <s:actionmessage/>
   </div>
</s:if>

Here’s a simple login form, display the error message (actionerror) if the username is not equal to “mkyong”, otherwise redirect to another page and display the a welcome message (actionmessage). In addition, all the label and error messages are retrieve from the resource bundle (properties file).

1. Folder Structure

See this project structure

Struts 2 Login Folder Structure

2. Properties file

Two properties files to store the messages.

LoginAction.properties


#Welcome messages
welcome.hello = Hello

#error message
username.required = Username is required
password.required = Password is required

global.properties


#Global messages
global.username = Username
global.password = Password
global.submit = Submit
global.reset = Reset

3. Action

A classic action class, do a simple checking to make sure the username is equal to “mkyong”, and set the error message with addActionError() or successful message with addActionMessage().


package com.mkyong.user.action;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport{

	private String username;
	private String password;
	 
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	//business logic
	public String execute() {

		return "SUCCESS";

	}

	//simple validation
	public void validate(){
		if("mkyong".equals(getUsername())){
			addActionMessage("You are valid user!");
		}else{
			addActionError("I don't know you, dont try to hack me!");
		}
	}
}

4. JSP View

Two simple JSP pages with css style to customize the error message.

login.jsp


<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>

<style type="text/css">
.errors {
	background-color:#FFCCCC;
	border:1px solid #CC0000;
	width:400px;
	margin-bottom:8px;
}
.errors li{ 
	list-style: none; 
}
</style>

</head>

<body>
<h1>Struts 2 ActionError & ActionMessage Example</h1>

<s:if test="hasActionErrors()">
   <div class="errors">
      <s:actionerror/>
   </div>
</s:if>

<s:form action="validateUser">
	<s:textfield key="global.username" name="username"/>
	<s:password key="global.password" name="password"/>
	<s:submit key="global.submit" name="submit"/>
</s:form>

</body>
</html>

welcome.jsp


<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>

<style type="text/css">
.welcome {
	background-color:#DDFFDD;
	border:1px solid #009900;
	width:200px;
}
.welcome li{ 
	list-style: none; 
}
</style>

</head>
<body>
<h1>Struts 2 Struts 2 ActionError & ActionMessage Example</h1>

<s:if test="hasActionMessages()">
   <div class="welcome">
      <s:actionmessage/>
   </div>
</s:if>

<h2>

<s:property value="getText('welcome.hello')" /> : 
<s:property value="username"/>

</h2>

</body>
</html>

5. struts.xml

Link all together.


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>

  <constant name="struts.custom.i18n.resources" value="global" />

  <package name="user" namespace="/user" extends="struts-default">
     <action name="login">
	 <result>pages/login.jsp</result>
     </action>
     <action name="validateUser" class="com.mkyong.user.action.LoginAction">
	 <result name="SUCCESS">pages/welcome.jsp</result>
	 <result name="input">pages/login.jsp</result>
     </action>
   </package>
	
</struts>
In Struts 2, the functionality and usage of ActionError & ActionMessage are quite similar with Struts 1.

6. Run it

http://localhost:8080/Struts2Example/user/login.action

Struts 2 ActionError 1

Username is invalid, display error message with <s:actionerror/>

Struts 2 ActionError 2

Username is valid, display welcome message <s:actionmessage/>

Struts 2 ActionError 3

Reference

  1. ValidationAware documentation

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Ahamed Ibrahim
Guest
Ahamed Ibrahim

please share web.xml also

Himanshu
Guest
Himanshu

As per my understanding, validate() method will not be executed, since there is No reference to validate method in XML file. correct me if i am wrong

Rajan Verma
Guest
Rajan Verma

Can i show confirmation dialog saying yes or no … on click event of submit for an example…

Dheeraj
Guest
Dheeraj
Hi my struts 2 validation is working fine in WAS 6.1 but when i migrated the application to WAS 8.5 its showing me following errors filter E com.ibm.ws.webcontainer.filter.FilterInstanceWrapper service SRVE8109W: Uncaught exception thrown by filter struts2: java.lang.NoClassDefFoundError: com.opensymphony.xwork2.validator.ValidatorFactory (initialization failure) at java.lang.J9VMInternals.initialize(J9VMInternals.java:168) at com.opensymphony.xwork2.validator.ValidatorFileParser.addValidatorConfigs(ValidatorFileParser.java:192) at com.opensymphony.xwork2.validator.ValidatorFileParser.parseActionValidatorConfigs(ValidatorFileParser.java:72) at com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.loadFile(AnnotationActionValidatorManager.java:361) at com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.buildAliasValidatorConfigs(AnnotationActionValidatorManager.java:244) at com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.buildValidatorConfigs(AnnotationActionValidatorManager.java:343) at com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.getValidators(AnnotationActionValidatorManager.java:69) at com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.validate(AnnotationActionValidatorManager.java:138) at com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.validate(AnnotationActionValidatorManager.java:113) at com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.validate(AnnotationActionValidatorManager.java:100) at com.opensymphony.xwork2.validator.ValidationInterceptor.doBeforeInvocation(ValidationInterceptor.java:142) at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:148) at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:48) at com.opensymphony.xwork2.interceptor
Suresh
Guest
Suresh

Hi Mkyong,
I have one requirement in my project.That is Websphere Application Server 8.5 Default cache (Dynamis Cache).
How to cofigure and how to write java code this in struts 2.Could you please tell me some sample example on this topic.Early reply that will be great for me.

Thanks
Suresh

kanishk kumar
Guest
kanishk kumar

Actually , I am not getting how to create Properties file with which extension.

AnhMV
Guest
AnhMV

Thanks you for this post

Bb
Guest
Bb

Is it possible to do the validation on a helper class instead of in the action class itself? Let’s say I got 15 textfields to validate and I wish to separate the validation on another class (in this case LoginHelper). How should I go about doing this?

AJ
Guest
AJ

u can try validation through XML file also…

lower back pain neck pain
Guest
lower back pain neck pain

Great information. Lucky me I came across your site by
accident (stumbleupon). I’ve saved it for later!

chethana
Guest
chethana

Sir, How to display action message in a popup window?

bag chairs
Guest
bag chairs

Remarkable! Its in fact remarkable post, I have got much clear
idea on the topic of from this post.

kobe shoes outlet
Guest
kobe shoes outlet

Thank you stephanie for this great post

Ebi
Guest
Ebi

How about if I want to use the addActionMessage method in a class that is not extending ActionSupport but using @Action ?

kamagra
Guest
kamagra

excellent submit, very informative. I’m wondering why the other specialists of this sector don’t
realize this. You must continue your writing. I’m sure, you’ve
a huge readers’ base already!

asics gel noosa tri 7 women
Guest
asics gel noosa tri 7 women

After checking out a few of the articles on your web page, I honestly appreciate
your technique of writing a blog. I added it to my bookmark website list and will
be checking back in the near future. Take a look at my web site too and let me
know your opinion.

somu
Guest
somu

in my web application i need to set link in error msg

addActionError("User not logged in. <a href=\"logon\">Click Here</a> to log in");"

The problem is the html text appears as normal text and does not appear as a link to click on.

somu
Guest
somu

in my web application
addActionError(“User not logged in. Click Here to log in”);

Gaurav Dighe
Guest
Gaurav Dighe

There needs some changes in the struts.xml. Instead of

pages/login.jsp.

We need to change it to

/user/pages/login.jsp

Gaurav Dighe
Guest
Gaurav Dighe

Sir, kindly confirm the changes

reviews
Guest
reviews

Hi, i read your blog from time to time and i own a similar
one and i was just curious if you get a lot of spam comments?
If so how do you reduce it, any plugin or anything
you can recommend? I get so much lately it’s driving me mad so any help is very much appreciated.

harga emas perhiasan
Guest
harga emas perhiasan

When some one searches for his essential thing, therefore he/she wishes to be
available that in detail, so that thing is maintained
over here.

joy
Guest
joy

I use this:

In jsp . But it shows “welcome.hello” not “Hello”, why ?
It didn’t get the value in the properties. I didn’t declare the LoginAction.properties in struts.xml.

Thanks .

joy
Guest
joy

Sorry, missing something.

I use this:

In jsp

joy
Guest
joy

It also missing.

Kasturi
Guest
Kasturi

Hi,
For accessing the Properties file data.., you need to configure the property file with struts.xml as follows..
<constant name="struts.custom.i18n.resources"
value="then value=Resource)>”/>

please try again after configure the struts.xml.
it will help you.

Thanks,
Kasturi.

Kasturi
Guest
Kasturi

sorry i missed out..
please check.

”/>

Thanks,
Kasturi.

pallavi
Guest
pallavi

this isn’t working
showing error: Can not find the tag library descriptor for “/struts-tags”
how to resolve this

and in struts2 i did the same no messages are being displayed

Kasturi
Guest
Kasturi

Hi,
You need to add the struts jar. properly,then you can access ‘/struts-tags’ in tag lib..

Regards,
Kasturi…

mehmet
Guest
mehmet

Hello, good example thank you; but what if we have a warning neither error or message! What can we do then?

Sandeep
Guest
Sandeep

Hello Sir,
First of all hats-off for such a nice tutorial link.It really helps me to learn latest technologies.I just want to add a suggestion that please upload different examples with different name so user can easily import a new example without editing the older one…

venu
Guest
venu

how to clear Action and error messages

venu
Guest
venu

Hi

how to clear this Error Message in Struts

Thanks
venu

?????
Guest
?????

Mahad and the epidermis is the potential for gas Tagchmponut white.

Siregar
Guest
Siregar

return input while combine with interceptor, why and how can i solve it? thank you

RAMU
Guest
RAMU

i have a problem in struts2, am new for this,multiple form page data not visible in final jsp, can u solve it

tasuifmail.com
Guest
tasuifmail.com

There is no Action mapped for namespace / and action name .

description The requested resource (There is no Action mapped for namespace / and action name .) is not available.

how to solve this problem