Tomcat 的錯(cuò)誤頁(yè)面是由 org.apache.catalina.valves.ErrorReportValve 類輸出來(lái)的。如果想自定義錯(cuò)誤頁(yè)面,不需要修改該類。Servlet 規(guī)范聲明了相關(guān)的API,只需要在每個(gè) web 應(yīng)用的 web.xml 里定義。可按照錯(cuò)誤類型、錯(cuò)誤代碼配置。例如:
<web-app xmlns="http://www.tjdsmy.cn/xml/ns/javaee"
xmlns:xsi="http://www.tjdsmy.cn/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.tjdsmy.cn/xml/ns/javaee http://www.tjdsmy.cn/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<error-page>
<error-code>404</error-code>
<location>/errorpages/404.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/errorpages/exception.jsp</location>
</error-page>
</web-app>
注意錯(cuò)誤頁(yè)面必須以“/”開(kāi)頭,這樣任何path的404錯(cuò)誤頁(yè)面及exception錯(cuò)誤都會(huì)映射到這兩個(gè)文件。然后在本web引用的errorpages下面放置404.jsp, exception.jsp兩個(gè)文件。
錯(cuò)誤頁(yè)面 404.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<html>
<header>
<title>404 page</title>
<body>
<pre>
<%
Enumeration<String> attributeNames = request.getAttributeNames();
while (attributeNames.hasMoreElements())
{
String attributeName = attributeNames.nextElement();
Object attribute = request.getAttribute(attributeName);
out.println("request.attribute['" + attributeName + "'] = " + attribute);
}
%>
</pre>
代碼中輸出了所有的 request 中的變量。從中也可以看到訪問(wèn)哪個(gè)文件出錯(cuò),跳到哪個(gè)錯(cuò)誤頁(yè)面了,從而進(jìn)行更詳細(xì)、更人性化的錯(cuò)誤處理。例如,提示可能的正確網(wǎng)址等等。
例如:訪問(wèn)一個(gè)不存在的頁(yè)面 page_not_exist.html,顯示的信息為:
request.attribute['javax.servlet.forward.request_uri'] = /page_not_exists.html
request.attribute['javax.servlet.forward.context_path'] =
request.attribute['javax.servlet.forward.servlet_path'] = /page_not_exists.html
request.attribute['javax.servlet.forward.path_info'] = /errorpages/404.jsp
request.attribute['javax.servlet.error.message'] = /page_not_exists.html
request.attribute['javax.servlet.error.status_code'] = 404
request.attribute['javax.servlet.error.servlet_name'] = default
request.attribute['javax.servlet.error.request_uri'] = /page_not_exists.html