Exception handling in Struts 2
There are very few differences in exception handling between Struts versions 1 and 2. This document describes the things to watch for.
Background
Exception flow:The base flow for exception handling in
Version 2 is the same as Struts 1 flow, and works as follows:
- When an exception is detected by internal logic invocation, the exception will be wrapped and handled in the BaseAction. In the handling logic, a new error execution unit will be created and invoked, which later will help to generate an error forward path.
- For the error path, the Struts 2 framework will take over control and route the page to a preconfigured error result. This can be a local or a global location configuration.
- After a page rendering request is dispatched, an error handling JSP will be executed which generates error results for browsers to consume.
Compared with Struts 1, the only difference happens in how the exception and messages are put into the default Struts framework.
In Struts 1, BaseAction puts the
exception into HttpServletRequest attributes by invoking the method saveErrors()
of Action. If a customer later wants to consume the error information from a JSP page, the customer
can use the <html:errors/>
tag to access the exception information.
Struts 2 uses a new tag <s:actionerrors/>
to help to display the error
messages in the page front.
Version 1 JSP content will resemble
this:
<logic:messagesPresent message="false">
<html:errors/>
</logic:messagesPresent>
By contrast, Version 2 content resembles the
following:
<s:if test="hasActionErrors()">
<div>
<s:actionerror/>
</div>
</s:if>