2012年11月13日 星期二

JSP or Struts simply show error page and exception inforamtion

1. Problem
In develop the web application by struts or jsp,
it has the requirement to show the error message,
but use the struts default exception handler method is complex to show data,
because it involve the bean, action setting for exception type.

I study the inline error page show and share it.


2. Solution
I use simple jsp handle object,
pageContext.exception and
pageContext.errorData


3. Example

Notice: if you use struts,
don't write the <global-exceptions> tag,
we will transfer the exception to the tomcat handle

A. in web.xml write
=============================================
<error-page>
        <error-code>404</error-code>
        <location>/error.jsp</location>
</error-page>
 
<error-page>
     <exception-type>java.lang.Throwable</exception-type>
      <location>/error.jsp</location>
</error-page>
=============================================



B. error.jsp
=============================================

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isErrorPage="true" %>
<html>
<head>
<title>Error Page</title>

 <style type="text/css">
h2{background:darkblue;color:white}
h3{background:darkblue;color:white}
.style1 {
    color: #66CCFF;
    font-size: x-large;
    font-weight: bold;
}
</style>


</head>
<body>
<span class="style1">Oops...</span><br>
<div>
A system error has occured. <br>
If the
problem persists, please report this information to the System Administrator.
</div>

<br/>
[<a href="./index.jsp">GoGack to index</a>]
[<a href="javascript:showDetails()">Show details</a> ]
[<a href="javascript:hideDetails()">Hide details</a> ]
<br/>


<table id="showDetailsLinkDiv" style="{display:none}"   cellspacing="0" width="100%" border="1">
 
    <tr valign="top">
        <td width="40%"><b>Error:</b></td>
        <td>${pageContext.exception}</td>
    </tr>
 
    <tr valign="top">
        <td><b>URI:</b></td>
        <td>${pageContext.errorData.requestURI}</td>
    </tr>
 
    <tr valign="top">
        <td><b>Status code:</b></td>
        <td>${pageContext.errorData.statusCode}</td>
    </tr>
 
    <tr valign="top">
    <td><b>Stack trace:</b></td>
    <td>
        <c:forEach var="trace"
                 items="${pageContext.exception.stackTrace}">
        <p>${trace}</p>
    </c:forEach>
    </td>
    </tr>

</table>

<script language="javascript">
   function showDetails() {
     document.getElementById("showDetailsLinkDiv").style.display = "inline";
   }
   function hideDetails() {
     document.getElementById("showDetailsLinkDiv").style.display = "none";
   }
</script>
</body>
</html>


=============================================


Reference:
http://geekexplains.blogspot.tw/2008/06/errorexception-handling-in-jsp-using.html

沒有留言:

張貼留言