web.xml 配置404和500錯誤的自定義頁面

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
    xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    
<error-page>
    <error-code>404</error-code>
    <location>/building.jsp</location>
</error-page>

<error-page>
    <error-code>500</error-code>
    <location>/error.jsp</location>
</error-page>
    
</web-app>


JSP頁面的關鍵在於

1 isErrorPage="true"

2 response.setStatus(HttpServletResponse.SC_OK);

等價於

response.setStatus(200);

error.jsp異常處理頁面形式一

<%@ page language="java" contentType="text/html; charset=GBK" isErrorPage="true" pageEncoding="UTF-8"%>
<%response.setStatus(HttpServletResponse.SC_OK);%>
<%
/** *//**
* 本頁面是在客戶查找的頁面無法找到的情況下調用的
*/
response.setStatus(HttpServletResponse.SC_OK);
%>
<body>
正在製作 <a href="javascript:history.go(-1)">返回</a>
<br/>
也可能頁面連接更改了,請按 F5 鍵刷新整個頁面看看,特別是菜單!
</body>

出錯頁面形式二

<%@ page language="java" contentType="text/html; charset=GBK" isErrorPage="true" pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*"%>
<%response.setStatus(HttpServletResponse.SC_OK);%>
<body>
程序發生了錯誤,有可能該頁面正在調試或者是設計上的缺陷.<br/>
你可以選擇<br/> <a href=<%=request.getContextPath()+"/forum/new.jsp" %>>反饋</a>
提醒我 或者<br/><a href="javascript:history.go(-1)">返回上一頁</a>
<hr width=80%>
<h2><font color=#DB1260>JSP Error Page</font></h2>
<p>An exception was thrown: <b> <%=exception.getClass()%>:<%=exception.getMessage()%></b></p>
<%
Enumeration<String> e = request.getHeaderNames();
String key;
while(e.hasMoreElements()){
  key = e.nextElement();
}
e = request.getAttributeNames();
while(e.hasMoreElements()){
  key = e.nextElement();
}
e = request.getParameterNames();
while(e.hasMoreElements()){
  key = e.nextElement();
}
%>
<%=request.getAttribute("javax.servlet.forward.request_uri") %><br>
<%=request.getAttribute("javax.servlet.forward.servlet_path") %>
<p>With the following stack trace:</p>
<pre>
<%
  exception.printStackTrace();
  ByteArrayOutputStream ostr = new ByteArrayOutputStream();
  exception.printStackTrace(new PrintStream(ostr));
  out.print(ostr);
%>
</pre>
<hr width=80%>
</body>


測試show.jsp顯示錯誤頁面

<%@ page language="java" contentType="text/html; charset=GBK" erorPage="error.jsp" pageEncoding="UTF-8"%>
<%
int i=10/0%>
發佈了28 篇原創文章 · 獲贊 14 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章