Wednesday, August 23, 2006

 

Struts error message handling

There is a lot of material written on how to handle error messages with struts, but I would like outline implementation for specific use case that I had to implement today.

Scenario:
There is a form that does some work Once user submit the form, action performed and user redirected back to the initial page with form, displaying either error message in red color or success message in green color.
Message should be displayed only once, and subsequent refresh of the page should not display neither success or error message. No ".do" url should ever appear in address bar

Solution:
Create "success" and "error" message bundles and use 2 different instances of tag to control presentation. Make sure that in the action code either "success" or "error" resources keys are passed, not both. Errors then saved on the session, in order to survive http redirect. jsp page has logic for transering error o

Important Implementation points:
Implementation Steps

1. Create SuccessResources.properties
#com.igrapp.uc1_strutserror.SuccessResources.properties
uc1_struts_error.success=This is a success

2. Create ErrorResources.properties
#com.igrapp.uc1_strutserror.ErrorResources.properties
uc1_struts_error.error=This is error


3.
Configure SuccessResources.properties and ErrorResources.properties in struts-config.xml
Add entries below to the struts-config.xml
<message-resources parameter="com.igrapp.u1_strutserror.ErrorResources" key="errorBundle" />
<message-resources parameter="com.igrapp.u1_strutserror.SuccessResources" key="successBundle"/>

4. Code action.
DynaActionForm f = (DynaActionForm)form;
ActionMessages msg = new ActionMessages();

String test = f.getString("test");
if ( test == null || test.trim().length() == 0 ) {
msg.add(null, new ActionMessage( "uc1_struts_error.error"));
} else {
msg.add(null, new ActionMessage( "uc1_struts_error.success"));

}

saveErrors(req.getSession(), msg);
return mapping.findForward("success");

4. Add action and DynaForm into struts-config.xml
...
<form-bean name="MyForm"
type="org.apache.struts.action.DynaActionForm">
<form-property name="test" type="java.lang.String"/>
</form-bean>
...
<action
path="/testaction"
type="com.igrapp.u1_strutserror.MyAction"
name="MyForm"
scope="request"
validate="false"
>
<forward
name="success"
path="/index.jsp"
redirect="true"
/>
</action>
....

5.
Add code to jsp page.
<%
Object o = session.getAttribute( "org.apache.struts.action.ERROR");
if ( o != null ) {
request.setAttribute( "org.apache.struts.action.ERROR", o);
session.removeAttribute( "org.apache.struts.action.ERROR");
}
%>
...


<font color="red"><html:errors bundle="errorBundle"/></font>
<font color="green"><html:errors bundle="successBundle" />
...


Download source archive from my personal web site at http://www.igorgrapp.com/files/struts_error_message.zip

This page is powered by Blogger. Isn't yours?