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