John Topley's Knowledgebase

Using Struts To Display Exception Details On A JSP

Monday, 22 December 2003

Jakarta Struts can be configured to use declarative exception handling with a global or ActionMapping scope. The class of exception to be caught and a JSP to display when the exception occurs may also be specified.

The code given below displays the exception message and the stack trace. A page-scope JavaBean named “exception” is defined that contains the Exception object that Struts has placed under the HTTP request key “org.apache.struts.action.EXCEPTION”. The bean is given the type “java.lang.Throwable” so that any runtime exceptions are caught and displayed too.

The Struts <bean:write> tag is then used to write the contents of that bean to the JSP. This displays the exception message. A scriptlet can be used to call the printStackTrace method, passing it a PrintWriter object that itself is passed the implicit “out” variable, so that the stack trace can be written to the page.

Note that typically when using Struts the text strings would be looked up from a resources file using the <bean:message> tag (not shown here).

Download 0032.txt

  • The JSP:
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>

<bean:define id="exception" name="org.apache.struts.action.EXCEPTION"
  type="java.lang.Throwable" />

<p>
  Exception message:
</p>
<p>
  <bean:write name="exception" />
</p>
<p>
  Stack trace:
</p>
<p>
  <%
    exception.printStackTrace(new java.io.PrintWriter(out));
  %>
</p>

top | index | previous | next | comments ()

home | archive | kb | media | about | contact | accessibility
Copyright © 2003 - 2005 John Topley. Made with CityDesk.