Java Servlet Exception Handling Example (original) (raw)

When a servlet generates an error developers can handle those exceptions in various ways, let’s say a user tries a URL that does not map to a servlet the user typically gets a 404 page. With the error listing in the deployment descriptor, we can handle those exceptions. In this tutorial, we will see how to tackle these exception handling in the Servlet.

1. Introduction

An exception is an event, which occurs during the execution of a program, which disrupts the normal flow of the program’s instructions. The process of converting the system error messages into user-friendly error messages is known as Exception Handling.

1.1 Servlet-Error Handling

A customized content can be returned to a web-client when a servlet generates an error. Developers can do that by adding the <error-page /> elements in the web.xml. The following table describes the elements developers can define within an error-page element.

Element Required or Optional Description
Optional A valid HTTP error code. For e.g. 500 etc.
Optional A fully-qualified class name of a Java exception type. For e.g. java.lang.RuntimeException etc.
Required The location of the resource which is displayed to the user in case of an error. For e.g. /myErrorPage.jsp etc.

If the destination i.e. <location> is a servlet or a JSP page:

1.1.2 Types of Error a Servlet/Filter can Throw

A servlet or filter may throw the following exceptions during the processing of a request:

Note: All other exceptions should be wrapped in javax.servlet.ServletException.

Here is a step-by-step guide for implementing the Servlet framework in Java.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 1: Servlet Exception Handling Application Project Structure

Fig. 1: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project.

Fig. 2: Create Maven Project

Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 3: Project Details

Fig. 3: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

Fig. 4: Archetype Selection

Fig. 4: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 5: Archetype Parameters

Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

4.0.0 JavaServletExceptionHandlingEx JavaServletExceptionHandlingEx 0.0.1-SNAPSHOT war

We can start adding the dependencies that developers want like Servlets, Junit etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the Servlet API. The rest dependencies will be automatically resolved by the Maven framework and the updated file will have the following code:

pom.xml

4.0.0 JavaServletExceptionHandlingEx JavaServletExceptionHandlingEx war 0.0.1-SNAPSHOT JavaServletExceptionHandlingEx Maven Webapp http://maven.apache.org javax.servlet javax.servlet-api 3.1.0 ${project.artifactId}

3.2 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 6: Java Package Creation

Fig. 6: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.servlet.

Fig. 7: Java Package Name (com.jcg.servlet)

Fig. 7: Java Package Name (com.jcg.servlet)

Once the package is created in the application, we will need to create the 2 different controller classes. Right-click on the newly created package: New -> Class.

Fig. 8: Java Class Creation

Fig. 8: Java Class Creation

A new pop window will open and enter the file name as: MyExceptionServlet. The servlet controller class will be created inside the package: com.jcg.servlet.

Fig. 9: Java Class (MyExceptionServlet.java)

Fig. 9: Java Class (MyExceptionServlet.java)

Repeat the step (i.e. Fig. 8) and enter the filename as: ErrorHandler. The error handler class to read the cookies will be created inside the package: com.jcg.servlet.

Fig. 10: Java Class (ErrorHandler.java)

Fig. 10: Java Class (ErrorHandler.java)

3.2.1 Implementation of Servlet that Generates an Error

This servlet is used to throw an error to test the configuration. Let’s see the simple code snippet that follows this implementation.

MyExceptionServlet.java

package com.jcg.servlet;

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

@WebServlet("/myExceptionServlet") public class MyExceptionServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    throw new ServletException("HTTP GET Method Is Not Supported.");
}

}

3.2.2 Implementation of Servlet Exception Handling

Developers will map this servlet in the servlet descriptor to handle all the exceptions. They can get the information about the exception that occurred from the request attributes. Let’s see the simple code snippet that follows this implementation.

ErrorHandler.java

package com.jcg.servlet;

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;

@WebServlet("/error") public class ErrorHandler extends HttpServlet {

private static final long serialVersionUID = 1L;

/***** This Method Is Called By The Servlet Container To Process A 'GET' Request *****/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    handleRequest(request, response);
}

public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    /***** Analyze The Servlet Exception *****/    		
    Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
    String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name");
    Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");

    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");

    /***** Print The Response *****/
    PrintWriter out = response.getWriter();
    String title = "Error/Exception Information";		
    String docType = "<!DOCTYPE html>\n";
    out.println(docType 
            + "<html>\n" + "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title>" + title + "</title></head>\n" + "<body>");

    if (throwable == null && statusCode == null) {
        out.println("<h3>Error Information Is Missing</h3>");			
    } else if (statusCode != 500) {
        out.write("<h3>Error Details</h3>");
        out.write("<ul><li><strong>Status Code</strong>?= "+ statusCode + "</li>");
        out.write("<li><strong>Requested URI</strong>?= "+ requestUri + "</li></ul>");
    } else {
        out.println("<h3>Exception Details</h3>");
        out.println("<ul><li><strong>Servlet Name</strong>?= " + servletName + "</li>");
        out.println("<li><strong>Exception Name</strong>?= " + throwable.getClass( ).getName( ) + "</li>");
        out.println("<li><strong>Requested URI</strong>?= " + requestUri + "</li>");
        out.println("<li><strong>Exception Message</strong>?= " + throwable.getMessage( ) + "</li></ul>");
    }

    out.println("<div> </div>Click <a id=\"homeUrl\" href=\"index.jsp\">home</a>");
    out.println("</body>\n</html>");
    out.close();
}

}

3.3 Servlet Exception Handling in the Servlet Descriptor

Let’s see the simple code snippet to configure the exception handling in the servlet.

web.xml

Error/Exception Information 404 /error 403 /error javax.servlet.ServletException /error java.io.IOException /error

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 11: How to Deploy Application on Tomcat

Fig. 11: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page will be displayed.

http://localhost:8085/JavaServletExceptionHandlingEx/myExceptionServlet

Server name (localhost) and port (8085) may vary as per your Tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 12: 500 – Servlet That Generates an Error

Fig. 12: 500 – Servlet That Generates an Error

If we will try to access an invalid URL that will result in 404 response, we will get a response like below image.

Fig. 13: 404 – Page Not Found

Fig. 13: 404 – Page Not Found

That’s all for this post. Happy Learning!!

6. Conclusion

In this section, developers learned how to tackle the Servlet 3.0 Exception Handling. Developers can download the sample application as an Eclipse project in the Downloads section. I hope this article served you with whatever developers were looking for.

7. Download the Eclipse Project

This was an example of Exception Handling in Servlets.

Photo of Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).