July 14, 2011

Declarative Exception Handling in Struts 2

1) Create an action class - ErrorProne.java - and place it in the src folder of the Web Application. The execute() method of this class throws an exception,

package info.icontraining.struts2;

public class ErrorProne { 
   public String execute() throws Exception {
      throw new Exception ( "Routine Code Explosion");
   }
}

2) Configure the action in the struts.xml file within the package element

<package ... >
   ...
   <global-results>
      <result name="Error">/error-struts2.jsp</result>
   </global-results>

   <global-exception-mappings>
      <exception-mapping exception="java.lang.Exception" result="Error"/>
   </global-exception-mappings>
   ...
   <action name="ErrorProne" class="info.icontraining.struts2.ErrorProne">
   ...
</package>

3) Create the custom JSP that will be displayed when the exception occurs - error-struts2.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
  <p>This is a custom error page that displays when an Exception is thrown in any Struts2 component</p>
  <br/>
  <s:property value="%{exception.message}" />
  <s:property value="%{exceptionStack}" />
</body>
</html>

3) Test the code with the following URL in the browser,

http://localhost:8080/WebAppName/ErrorProne.action

No comments:

Post a Comment