Servlet exception handling
When a Servlet throws an exception, the Web container searches web.xml using the exception-type element for a configuration that matches the type of exception thrown.
You must use the error-page element in web.xml to specify that the appropriate Servlet call should be made for a specific Exception or HTTP Status Code .
web.xml Configuration
Assume that there is an ErrorHandler Servelt that is called when any defined exception or error occurs. The following will be the items created in web.xml.
<!-- servlet 定义 --> <servlet> <servlet-name>ErrorHandler</servlet-name> <servlet-class>ErrorHandler</servlet-class> </servlet> <!-- servlet 映射 --> <servlet-mapping> <servlet-name>ErrorHandler</servlet-name> <url-pattern>/ErrorHandler</url-pattern> </servlet-mapping> <!-- error-code 相关的错误页面 --> <error-page> <error-code>404</error-code> <location>/ErrorHandler</location> </error-page> <error-page> <error-code>403</error-code> <location>/ErrorHandler</location> </error-page> <!-- exception-type 相关的错误页面 --> <error-page> <exception-type> javax.servlet.ServletException </exception-type > <location>/ErrorHandler</location> </error-page> <error-page> <exception-type>java.io.IOException</exception-type > <location>/ErrorHandler</location> </error-page>
If you want to have a common error handler for all exceptions, you should define the following error-page instead of defining a separate error-page element for each exception:
<error-page> <exception-type>java.lang.Throwable</exception-type > <location>/ErrorHandler</location> </error-page>
The following are the points to note about the above web.xml exception handling:
Servelt ErrorHandler is defined in the same way as other Servelts and is configured in web.xml.
If an error status code occurs, whether it is 404 (Not Found) or 403 (Forbidden), the Servlet of ErrorHandler will be called.
If the web application throws ServletException or IOException, then the web container will call the ErrorHandler's Servlet.
You can define different error handlers to handle different types of errors or exceptions. The above examples are very general and I hope you can understand the basic concepts through examples.
Request Attributes - Error/Exception
The following is a list of request attributes that can be accessed by the error handling Servlet to analyze the nature of the error/exception.
Serial Number | Properties & Description |
---|---|
1 | javax.servlet .error.status_code This attribute gives the status code, which can be stored and analyzed after being stored as the java.lang.Integer data type. |
2 | ##javax.servlet.error.exception_typeThis attribute gives information about the exception type. The exception type can be stored. And can be analyzed after being stored as java.lang.Class data type. |
javax.servlet.error.messageThis attribute gives information about the exact error message. The information can be stored. And can be analyzed after being stored as java.lang.String data type. | |
##javax.servlet.error.request_uri | This attribute gives information about the URL calling the Servlet. The information can be stored , and can be analyzed after being stored as java.lang.String data type. |
##javax.servlet.error.exception | This attribute gives the information generated by the exception. The information can be stored and Can be analyzed after being stored as java.lang.Throwable data type. | 6
This attribute gives the name of the Servlet. The name can be stored and Can be parsed after being stored as java.lang.String data type. | Servlet Error Handler ExampleThe following is a Servlet instance that will handle any error or exception that you define. This example gives you a basic understanding of exception handling in Servlets, and you can use the same concepts to write more complex exception handling applications: // 导入必需的 java 库 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // 扩展 HttpServlet 类 public class ErrorHandler extends HttpServlet { // 处理 GET 方法请求的方法 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 分析 Servlet 异常 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"; } // 设置响应内容类型 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>"); } // 处理 POST 方法请求的方法 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } Compile in the usual wayErrorHandler.java, put your class files into <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes. Let us add the following configuration in the web.xml file to handle exceptions: <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> Now, try to use a Servlet that will generate an exception, or enter a wrong URL, which will trigger the Web The container calls the ErrorHandler Servlet and displays the appropriate message. For example, if you enter a wrong URL, then it will display the following result: The status code : 404 The above code may not work properly in some web browsers. So try to use Mozilla and Safari browsers, they should work fine in both browsers. |