错误处理程序 Servlet 示例
这个例子会让你对 Servlet 中的异常处理有基本的了解,但你可以使用相同的概念编写更复杂的过滤器应用程序 -
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class ErrorHandler extends HttpServlet {
// Method to handle GET method request.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Analyze the servlet exception
Throwable throwable = (Throwable)
request.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer)
request.getAttribute("javax.servlet.error.status_code");
String servletName = (String)
request.getAttribute("javax.servlet.error.servlet_name");
if (servletName == null) {
servletName = "Unknown";
}
String requestUri = (String)
request.getAttribute("javax.servlet.error.request_uri");
if (requestUri == null) {
requestUri = "Unknown";
}
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Error/Exception Information";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n");
if (throwable == null && statusCode == null) {
out.println("<h2>Error information is missing</h2>");
out.println("Please return to the <a href=\"" +
response.encodeURL("http://localhost:8080/") +
"\">Home Page</a>.");
} else if (statusCode != null) {
out.println("The status code : " + statusCode);
} else {
out.println("<h2>Error information</h2>");
out.println("Servlet Name : " + servletName + "</br></br>");
out.println("Exception Type : " + throwable.getClass( ).getName( ) + "</br></br>");
out.println("The request URI: " + requestUri + "<br><br>");
out.println("The exception message: " + throwable.getMessage( ));
}
out.println("</body>");
out.println("</html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
编译 ErrorHandler.java 以通常的方式并将您的类文件放入 /webapps/ROOT/WEB-INF/classes.
让我们在 web.xml 中添加以下配置来处理异常 -
<servlet>
<servlet-name>ErrorHandler</servlet-name>
<servlet-class>ErrorHandler</servlet-class>
</servlet>
<!-- servlet mappings -->
<servlet-mapping>
<servlet-name>ErrorHandler</servlet-name>
<url-pattern>/ErrorHandler</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/ErrorHandler</location>
</error-page>
<error-page>
<exception-type>java.lang.Throwable</exception-type >
<location>/ErrorHandler</location>
</error-page>
现在尝试使用引发任何异常或键入错误 URL 的 servlet,这将触发 Web 容器调用 ErrorHandlerservlet 并按照编程显示适当的消息。例如,如果您输入了错误的 URL,它将显示以下结果 -
以上代码可能不适用于某些 Web 浏览器。所以尝试使用 Mozilla 和 Safari,它应该可以工作。