Exception Handling in Servlet

Exception Handling in Servlet with Examples

In this article, I am going to discuss Exception Handling in Servlet. Please read our previous article where we discussed CRUD Operations in Servlet with Examples. At the end of this article, you will understand how servlet handles exceptions with an example.

Exception Handling in Servlet

The web container searches the configurations in web.xml when a servlet throws an exception which uses the exception-type element for a match with the thrown exception type. When our application throw exception, servlet container processes the exception and generate a HTML response since browser understand only HTML. Same goes with other error codes like 404, 403, etc. Servlet API provides support for custom exception and error handler servlets that we’ll configure in deployment descriptor. The whole purpose of these servlets is to handle the Exception or Error raised by application and send HTML response that’s useful for the user. We will provide link to application home page or some details to let user know what went wrong.

web.xml configuration

We can configure the errors in web.xml file like Error-code related error pages

Syntax:
<error-page>
<error-code> code</error-code>
<location>/url</location>
</error-page>
Example:
<error-page>
<error-code> 404</error-code>
<location>/ErrorHandler</location>
</error-page>

Exception-type related error pages

Syntax:
<error-page>
<exception-type>exception type</exception-type>
<location>/url</location>
</error-page>
Example:
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/ErrorHandler</location>
</error-page>

Points to Note:
  1. The servlet ErrorHandler is configured in web.xml file and is defined in usual way as any other servlet.
  2. The ErrorHandler servlet would be called if there is an error with status code either 404INot Found) or 403 (Forbidden).
  3. The web container invokes the /ErrorHandler servlet if the web application throws either ServletException or IOException.
  4. We can define different Error Handlers to handle different types of errors or exceptions.
Request Attributes – Errors/Exception
  1. status_code: It gives status code which can be stored and analyzed after storing in a java.lang.Integer data type.
  2. exception_type: It gives information about the exception type which can be stored and analyzed after storing in a java.lang.Class data type.
  3. message: It gives information exact error message which can be stored and analyzed after storing in a java.lang.String data type.
  4. request_uri: It gives information about URL calling the servlet and it can be stored and analyzed after storing in a java.lang.String data type.
  5. exception: It gives information about the exception raised, which can be stored and analyzed.
  6. servlet_name: It gives servlet names which can be stored and analyzed after storing in a java.lang.String data type.
Example

In this example, you will get a basic understanding of Exception Handling in Servlet. You can even use the same concept to write more sophisticated filter applications.

ErrorHandler.java
// 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);
    }
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 id="WebApp_ID" version="4.0">
 <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>
</web-app>
Output

Run your ErrorHandler.java code, as usual, you will get the following output.

Exception Handling in Servlet

Now try entering some different URL, the expected output will be the following:

Exception Handling in Servlet with Examples

In the next article, I am going to discuss Servlet with Annotation. Here, in this article, I try to explain Exception Handling in Servlet. I hope you enjoy this Exception Handling in Servlet with Examples article.

Leave a Reply

Your email address will not be published.