2013-11-28 125 views
0

好的,我對這個JSP的東西有點新,所以請不要把它釘在十字架上,如果這不是正確的做法。在JSP中打印堆棧跟蹤

我需要在error.jsp頁面中打印stackTrace,不僅是針對它接收到的異常,還針對所有原因鏈。於是,我開始把這個在我的web.xml:

<error-page> 
    <exception-type>java.lang.Throwable</exception-type> 
    <location>/error.jsp</location> 
</error-page> 

於是,我寫了這個文件的error.jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ page isErrorPage="true" %> 
<%@ page import="java.lang.Throwable" %> 
<%@ page import="java.lang.StackTraceElement" %> 

<html> 
    <head> 
     <title>An Error!</title> 
    </head> 

    <body> 
      <h1>An Error!</h1> 
      <table 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> 

      <% 
       Throwable cause = pageContext.getException().getCause(); 
       while(cause != null) { 
      %> 

       <tr valign="top"> 
        <td><b>Caused by:</b></td> 
        <td> 
         <% out.println(cause); %> 
        </td> 
       </tr> 

       <tr valign="top"> 
        <td><b>Stack trace:</b></td> 
        <td> 
         <% 
         StackTraceElement[] stackTrace = cause.getStackTrace(); 
         for (int i = 0; i < stackTrace.length; i++) { 
          %> <p> <% 
          out.println(stackTrace[i]); 
          %> </p> <% 
         } 
         %> 
        </td> 
       </tr> 

      <% cause = cause.getCause(); //Get next cause for the while loop 
      } 

      if (cause == null){ 
       %> 
        <tr valign="top"> 
         <td><b>No further Cause</b></td> 
        </tr> 
       <%   
      } 

     %> 

     </table> 
    </body> 
</html> 

它的正常工作和做的工作相當不錯,但我認識到這是一個醜陋的黑客。有沒有辦法更優雅地做到這一點?

謝謝

編輯:

忘記提到的部分代碼來源:http://www.tutorialspoint.com/jsp/jsp_exception_handling.htm

回答

0

看標題爲「使用JSTL標記爲錯誤頁面」教程的部分。 JSTL標籤是編寫更乾淨的JSP的幾種方法之一。正如您已經注意到的那樣,JSP中任何scriptlet(即Java)代碼的存在都很難看。 JSTL爲各種JSP範圍(頁面,請求,會話,應用等)提供了乾淨的語法來引用數據,而無需編寫Java代碼。如果您計劃進行JSP開發,我建議您花時間熟悉一下這個主題。這將是值得的。