Servlet Exception Handling

When a Servlet throws an exception, the Web container, in the [web.xml] that uses the exception-type element,web.xmlsearches for a configuration that matches the thrown exception type.

You must use in web.xml theerror-pageelement to specify that for a specificexceptionor HTTPstatus code,the corresponding Servlet call should be made.

web.xml Configuration

Suppose there is aErrorHandlerServlet that is invoked when any defined exception or error occurs. The following will be the entry 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 a generic 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 points to note about the web.xml exception handling above:

  • The Servlet ErrorHandler is defined in the same way as other Servlets, and is configured in web.xml.
  • If any error status code occurs, whether it is 404 (Not Found) or 403 (Forbidden), the ErrorHandler Servlet will be invoked.
  • If the Web application throwsServletExceptionorIOException, then the Web container will invoke the ErrorHandler Servlet.
  • You can define different error handlers to handle different types of errors or exceptions. The above example is very generic; we hope you can understand the basic concepts through the example.

Request Attributes - Error/Exception

The following is a list of request attributes that the error-handling Servlet can access, used to analyze the nature of the error/exception.

No.Attribute & Description
1javax.servlet.error.status_code
This attribute gives the status code, which can be stored and analyzed after being stored as a java.lang.Integer data type.
2javax.servlet.error.exception_type
This attribute gives information about the exception type, which can be stored and analyzed after being stored as a java.lang.Class data type.
3javax.servlet.error.message
This attribute gives information about the exact error message, which can be stored and analyzed after being stored as a java.lang.String data type.
4javax.servlet.error.request_uri
This attribute gives information about the URL that called the Servlet, which can be stored and analyzed after being stored as a java.lang.String data type.
5javax.servlet.error.exception
This attribute gives information about the exception that was thrown, which can be stored and analyzed after being stored as a java.lang.Throwable data type.
6javax.servlet.error.servlet_name
This attribute gives the name of the Servlet, which can be stored and analyzed after being stored as a java.lang.String data type.

Servlet Error Handler Example

The following is a Servlet instance that will act as the error handler for any errors or exceptions 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
    {
        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;charset=UTF-8");
    
        PrintWriter out = response.getWriter();
        String title = "Example Error/Exception 信息";
       
        String docType = "<!DOCTYPE html>\n";
        out.println(docType +
            "<html>\n" +
             "<head><title>" + title + "</title></head>\n" +
             "<body bgcolor=\"#F0F0F0\">\n");
           out.println("<h1>Example异常信息实例演示</h1>");
           if (throwable == null && statusCode == null){
              out.println("<h2>错误信息丢失</h2>");
              out.println("请返回 <a href=\"" + 
            response.encodeURL("http://localhost:8080/") + 
                "\">主页</a>。");
           }else if (statusCode != null) {
              out.println("错误代码 : " + statusCode);
        }else{
               out.println("<h2>错误信息</h2>");
              out.println("Servlet Name : " + servletName + 
                              "</br></br>");
              out.println("异常类型 : " + 
                              throwable.getClass( ).getName( ) + 
                              "</br></br>");
              out.println("请求 URI: " + requestUri + 
                              "<br><br>");
              out.println("异常信息: " + 
                                  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 to web.xml to handle exceptions:

<?xml version="1.0" encoding="UTF-8"?>  
<web-app>  
<servlet>
        <servlet-name>ErrorHandler</servlet-name>
        <servlet-class>com.example.test.ErrorHandler</servlet-class>
</servlet>
<!-- servlet mappings -->
<servlet-mapping>
        <servlet-name>ErrorHandler</servlet-name>
        <url-pattern>/TomcatTest/ErrorHandler</url-pattern>
</servlet-mapping>
<error-page>
    <error-code>404</error-code>
    <location>/TomcatTest/ErrorHandler</location>
</error-page>
<error-page>
    <exception-type>java.lang.Throwable</exception-type >
    <location>/ErrorHandler</location>
</error-page>
</web-app>  

Now, try using a Servlet that will throw an exception, or enter an incorrect URL, which will trigger the Web container to invoke theErrorHandlerServlet, and display an appropriate message. For example, if you enter an incorrect URL (e.g., http://localhost:8080/TomcatTest/UnKonwPage), it will display the following result:

Other Extensions