Java Servlet Exception Handling Example
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.
- Programmatically exception handling mechanism: The approach to use try and catch block in the Java code to handle exceptions is known as programmatically exception handling mechanism
- Declarative exception handling mechanism: The approach to use the
XML
tags in theweb.xml
file to handle the exception is known as declarative exception handling mechanism. This mechanism is useful if exception is common for more than one servlet program
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 |
---|---|---|
<error-code> | Optional | A valid HTTP error code. For e.g. 500 etc. |
<exception-type> | Optional | A fully-qualified class name of a Java exception type. For e.g. java.lang.RuntimeException etc. |
<location> | Required | The location of the resource which is displayed to the user in case of an error. For e.g. /myErrorPage.jsp etc. |
1.1.1 Request Attributes Related to Error Information
If the destination i.e. <location>
is a servlet or a JSP page:
- The original request and response objects are passed to the destination
- The request path and the attributes are set as if a
requestDispatcher.forward
to the error resource had been performed - The request attributes are set to the following:
Request Attributes Type javax.servlet.error.status_code
java.lang.Integer
javax.servlet.error.exception_type
java.lang.Class
javax.servlet.error.message
java.lang.String
javax.servlet.error.exception
java.lang.Throwable
javax.servlet.error.request_uri
java.lang.String
javax.servlet.error.servlet_name
java.lang.String
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:
- Unchecked Exceptions i.e.
java.lang.RuntimeException
, Error, and subclasses javax.servlet.ServletException
or subclassesjava.io.IOException
or subclasses
Note: All other exceptions should be wrapped in javax.servlet.ServletException
.
2. Java Servlet Exception Handling Example
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!
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
.
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.
Select the ‘Maven Web App’ Archetype from the list of options and click next.
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
.
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
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>JavaServletExceptionHandlingEx</groupId> <artifactId>JavaServletExceptionHandlingEx</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project>
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
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>JavaServletExceptionHandlingEx</groupId> <artifactId>JavaServletExceptionHandlingEx</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>JavaServletExceptionHandlingEx Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> </build> </project>
3.2 Java Class Creation
Let’s create the required Java files. Right-click on src/main/java
folder, New -> Package
.
A new pop window will open where we will enter the package name as: 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
.
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
.
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
.
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
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Error/Exception Information</display-name> <!-- Error Code Related Error Pages --> <error-page> <error-code>404</error-code> <location>/error</location> </error-page> <error-page> <error-code>403</error-code> <location>/error</location> </error-page> <!-- Exception Type Related Error Pages --> <error-page> <exception-type>javax.servlet.ServletException</exception-type> <location>/error</location> </error-page> <error-page> <exception-type>java.io.IOException</exception-type> <location>/error</location> </error-page> </web-app>
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
.
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!
If we will try to access an invalid URL that will result in 404
response, we will get a response like below image.
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.
You can download the full source code of this example here: JavaServletExceptionHandlingEx
Dear Yatin Batra.
Thank You.
Sincerely : Laszlo Tatai
Thank you Laszlo! :) Keep following JavaCodeGeeks for more content!