Exception Handling in Servlet

As of now, we have discussed Filter in Servlet. In this article, we will discuss an Exception in Servlet. As we know, Exception is an unwanted event that arises during the execution of a program, therefore these need to be handled in the program. So, In this article, we will discuss How Exception is handled in Servlet.

What is Exception in Servlet?

The Exception in Servlet is an abnormal condition that arises during the execution of a program that interrupts the normal flow of execution.

  • Servlet provides support for Exception that is configured in the web.xml file of the application.
  • The whole purpose of these is to handle the Exception and send a useful response to the user.
  • Following is the web.xml file configuration for Exception Handling.
<!--Servlet-->
<servlet>
  <servlet-name>ErrorHandle</servlet-name>
  <servlet-class>ErrorHandle</servlet-class>
<servlet> 
<servlet-mapping>
  <servlet-name>ErrorHandle</servlet-name>
  <url-pattern>/ErrorHandle</url-pattern>
</servlet-mapping>
<!--Error code-->
<error-page>
  <error-code>403</error-code>
  <location>/ErrorHandle</location>
</error-page>
<!--Exception type--->
<error-page>
  <exception-type>javax.servlet.ServletException</exception-type>
  <location>/ErrorHandle</location>
</error-page>

For generic Exception, We should define the following error-page instead of defining separate error-page elements.

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

Request Attributes for Exception

  • javax.servlet.error.status_code: This attribute gives us the status code.
  • javax.servlet.error.exception_type: This attribute gives us the type of exception that occurred. As in the above web.xml file, the ServletException type is used.
  • javax.servlet.error.message: This attribute gives us the exact error message.
  • javax.servlet.error.request_uri: This attribute gives us the information on the URL calling the servlet.
  • javax.servlet.error.exception: This attribute gives us the information of Exception raised.
  • javax.servlet.error.servlet_name: This attribute gives us the servlet-name.

Let’s see the Example for Exception Handling in Servlet

In this example first, we will create a single servlet and web.xml file that will give you an understanding of attributes in Exception Handling.

Demo.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Demo
 */
@WebServlet("/Demo")
public class Demo extends HttpServlet {
  private static final long serialVersionUID = 1L;

  /**
   * @see HttpServlet#HttpServlet()
   */
  public Demo() {
    super();
    // TODO Auto-generated constructor stub
  }

  protected 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");
    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 info is missing</h2>");
      out.println("Please return to the <a href=\"" + response.encodeURL("http://localhost:8088/")
          + "\">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>");
  }
}

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  id="WebApp_ID" version="3.0">
  <display-name>ExceptionHandlerDemo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Demo</servlet-name>
    <servlet-class>Demo</servlet-class>
  </servlet>

  <!-- servlet mappings -->
  <servlet-mapping>
    <servlet-name>Demo</servlet-name>
    <url-pattern>/Demo</url-pattern>
  </servlet-mapping>

  <error-page>
    <error-code>404</error-code>
    <location>/Demo</location>
  </error-page>

  <error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/Demo</location>
  </error-page>
</web-app>

Output

In this, if you type the wrong URL. You will get the following output which means we have handled the Error 404 page.

Thus we have seen How to Handle Exception in Servlet. Let us see How to handle cookies in servlet in detail in the next article.