原文:http://xiaoxuejie.iteye.com/blog/1338609
一:Tomcat Error Page配置
如果JSP頁面出現異常,就會轉到tomcat自動的那個異常頁面,頁面不怎麼友好。jsp標準中提供了error page的配置,可以自己定義當出現錯誤時跳轉到哪個頁面。這個配置在web.xml裏面進行配置,下面一步步來實現自定義錯誤頁面。
1.首先,在web.xml加入下面的標籤:
<error-page>
<error-code>400</error-code>
<location>/400.html</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
解釋一下,error-code是錯誤代碼,location是轉向頁面。如果這個配置成功,當服務器出現這個錯誤代碼的時候,就會跳轉到location這個頁面。location可以是html文件,也可以是jsp頁面。
2.下面編寫一下error.jsp頁面的代碼,例如:
<%page contentType="text/html;charset=Big5" isErrorPage="true"%>
<html>
<head><title>出現錯誤</title></head>
<body>
<H1>錯誤:</H1><%=exception%>
<H2>錯誤內容:</H2>
<%
exception.printStackTrace(response.getWriter());
%>
</body>
</html>
因爲這個頁面調用了exception內置對象,所以isErrorPage必須爲true。
3.不僅可以根據html的錯誤代碼來條轉頁面,也可以按異常類型來進行跳轉,例如:
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/errorhandler.jsp</location>
</error-page>
不僅可以使用jsp內置exception對象來取得異常,也可以取得request中的attribute。例如:
<%@Page contentType="text/html;charset=Big5" isErrorPage="true"%>
<html>
<head><title>錯誤信息</title></head>
<body>
錯誤碼: <%=request.getAttribute("javax.servlet.error.status_code")%> <br>
信息: <%=request.getAttribute("javax.servlet.error.message")%> <br>
異常: <%=request.getAttribute("javax.servlet.error.exception_type")%> <br>
</body>
</html>
二: Error Page在IE下不能轉發的問題
這是IE自身的設定導致的,經過百度,找到幾個解決辦法:1, IE設定 工具-->Internet選項-->高級--->顯示http友好錯誤信息(取消選擇) , 這樣就可以了
2, 設置指定錯誤頁頁狀態爲正常,來告訴IE這不是一個服務器錯誤, 從而不顯示IE的自定義錯誤頁
<%
response.setStatus(200); // 200 = HttpServletResponse.SC_OK
%>
3, 把錯誤頁做大一點,弄個幾百K 就可以顯示錯誤頁面 (加一個div塊,display設爲none就可以了),這個問題比較奇怪