Java – How to display success message in Struts

jakarta-eejavastruts

we could display errors in Struts by doing actionErrors.add(key, new Actionmessage("string")), addErrors(request, actionErrors); and then outputting it into a JSP page via

I'm wondering, how do I output success messages in Struts? How do you normally/conventionally do it?

Best Answer

On Struts 1 you can use ActionMessage instances to represent a message to be displayed on a JSP

ActionMessages messages = new ActionMessages();
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message1");
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message2");
saveMessages(request, messages); // storing messages as request attributes

"message1" and "message2" are keys for you resources property file. Very similar to ActionError handling

Displaying the messages on JSP is similar to action errors, but you must include the property "message"

<logic:messagesPresent message="true">
   <html:messages id="message" message="true">
     <bean:write name="message"/><br/>
   </html:messages>
</logic:messagesPresent>

In this example the messages were stored as attribute requests. If you want to have control over the attribute name you can specify any attribute name

ActionMessages messages = new ActionMessages();
messages.add("appMessage", new ActionMessage("message1");
saveMessages(request, messages); // storing messages as request attributes

Now the messages are stored under the request attribute "appMessage". Setting a custom attribute name may be useful if you want to use JSTL tags instead of Struts tags on JSP for example

Additionally you may save action messages on session scope.

saveMessages(request.getSession(), messages); // storing messages as request attributes

You can use this feature to show sticky messages over user session, such as user full name for example.