Struts error reporting
Struts was using two different classes to report errors and messages back to the user: ActionErrors and ActionMessages. As the ActionErrors and ActionError classes were deprecated since 1.2.0. version I will talk now only about ActionMessages and ActionMessage.
From an action class when you need to send a message to the page all that must be done is to set it up using the ActionMessages class.
Struts ActionMessages example:
ActionMessages actionMessages = new ActionMessages();
actionMessages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(”my.error”));
saveMessages(request, actionMessages);
This error will be displayed in JSP using:
<logic:messagesPresent message="true">
<html:messages message=”true” id=”msg”>
<bean:write name=”msg” ignore=”true”/>
</html:messages>
</logic:messagesPresent>
One issue to be mentioned here is that “my.error” is a key that will be used to look up message text in an appropriate message resources database, like Application.properties for example.
But if you do not need to report a generic error message you will have to use the following code:
ActionMessages actionMessages = new ActionMessages();
actionMessages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(”my.error”));
request.setAttribute(”warnings”, actionMessages);
This code will set up an error message under an arbitrary key and display it with the html:messages tag:
<html:messages name="warnings" id="message">
<bean:write name=”message” />
</html:messages>
There are some differences to be noticed here.
- There is no message=”true” attribute present that signals to look up for an ActionMessage under the Globals.MESSAGE_KEY.
- There is no <logic:messagePresent> tag as it will not be validated.
If your error message gets constructed dynamically the ActionMessage class offers four constructors that allow message customization with up to four parameters.
So the message:
new ActionMessage("my.error", "p1", "p2", "p3", "p4")
where
my.error=You are not allowed to do {0}, {1}, {2} and {3}
will render
You are not allowed to do p1, p2, p3 and p4

Hi,
Lucid and quite useful. Thanks.