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 ... >
      <result name="Error">/error-struts2.jsp</result>

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

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

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

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


No comments:

Post a Comment