Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Servlet exception handling


May 14, 2021 Servlet


Table of contents


Servlet exception handling

When a servlet throws an exception, the web container searches for a configuration that matches the type of exception thrown in the web .xml that uses the exception-type element.

You must use the error.xml element in the web page to specify that the appropriate servlet call is made for a specific exception or HTTP status code.

Web .xml configuration

Suppose you have an ErrorHandler servlet that is called when any defined exception or error occurs. The following will be the .xml created in the web game.

<!-- 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 a separate error-page element for each exception:

<error-page>
    <exception-type>java.lang.Throwable</exception-type >
    <location>/ErrorHandler</location>
</error-page>

Here are some things to .xml the above web site:

  • Servelt ErrorHandler is defined in the same way as other Servelts and is configured .xml the web server.
  • ErrorHandler's servlet is called if an error status code appears, whether it is 404 (Not Found not found) or 403 (Forbidden prohibited).
  • If a Web application throws a ServletException or IOException, the Web container calls ErrorHandler's servlet.
  • You can define different error handlers to handle different types of errors or exceptions. The above example is very generic, and I hope you can understand the basic concepts through the instance.

Request property - error/exception

The following is a list of request properties that can be accessed by the servlet for error handling to analyze the nature of the error/exception.

Serial number Properties & Description
1 javax.servlet.error.status_code
This attribute gives a status code, and the status code can be stored and can be analyzed after being stored as a Java.lang.integer data type.
2 javax.servlet.error.exception_type
This attribute gives an exception type information, and the exception type can be stored and can be analyzed after being stored as java.lang.class data type.
3 javax.servlet.error.message
This attribute gives the authentication error message, and the information can be stored and can be analyzed after being stored as java.lang.String data type.
4 javax.servlet.error.request_uri
This property gives information about the URL call servlet, and the information can be stored and can be analyzed after the data type is stored as Java.lang.String.
5 javax.servlet.error.exception
This property gives an exception generated information, and the information can be stored and can be analyzed after being stored as java.lang.Throwable data type.
6 javax.servlet.error.servlet_name
This attribute gives the name of the servlet, the name can be stored and can be analyzed after being stored as java.lang.string data type.

An instance of a servlet error handler

The following is an example of a servlet that will handle any error handler that you define when an error or exception occurs.

This example gives you a basic understanding of exception handling in servlets, and you can write more complex exception handling applications using the same concepts:

// 导入必需的 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 class="tutheader">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 the ErrorHandler .java in the usual way and put your class files in the .lt; Tomcat-installation-directory/webapps/ROOT/WEB-INF/classes.

Let's add .xml the web server file to handle the exception:

<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 using a servlet that produces an exception, or enter an incorrect URL, which triggers the Web container to call ErrorHandler's servlet and display the appropriate message. For example, if you enter an incorrect URL, it will show the following results:

The status code : 404

The above code may not work properly in some web browsers. Therefore, try Mozilla and Safari browsers, where they should work.