Info |
---|
The code for this tutorial, exception_handling, is available for checkout at https://svngithub.com/apache.org/repos/asf/struts/sandbox/trunk/struts2examplesstruts-examples. |
Introduction
In this tutorial we'll explore how to enable the Struts 2 framework to handle any uncaught exceptions generated by a web application. Struts 2 provides robust exception handling, including the ability to automatically log any uncaught exceptions and redirect the user to a error web page.
...
To enable global exception handling you need to add two nodes to struts.xml: global-exception-mapping and global-results. For example examine struts.xml from the exception_handling project.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
<global-results>
<result name="securityerror">/securityerror.jsp</result>
<result name="error">/error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="org.apache.struts.register.exceptions.SecurityBreachException" result="securityerror" />
<exception-mapping exception="java.lang.Exception" result="error" />
</global-exception-mappings>
|
...
If you need to handle an exception in a specific way for a certain action you can use the exception-mapping node within the action node.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
<action name="actionspecificexception" class="org.apache.struts.register.action.Register" method="throwSecurityException">
<exception-mapping exception="org.apache.struts.register.exceptions.SecurityBreachException"
result="login" />
<result>/register.jsp</result>
<result name="login">/login.jsp</result>
</action>
|
...
To set these parameter values for all actions that use a specific stack of interceptors in a package include the following in struts.xml just after the opening package node.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
<interceptors>
<interceptor-stack name="appDefaultStack">
<interceptor-ref name="defaultStack">
<param name="exception.logEnabled">true</param>
<param name="exception.logLevel">ERROR</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="appDefaultStack" />
|
...
You can display information about the exception in the browser if you want by using s:property tags with a value of exception and exceptionStack. For example in error.jsp is this markup.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
<h4>The application has malfunctioned.</h4>
<p> Please contact technical support with the following information:</p>
<h4>Exception Name: <s:property value="exception" /> </h4>
<h4>Exception Details: <s:property value="exceptionStack" /></h4>
|
...