My name is Vasyl Khrystiuk‎ > ‎process‎ > ‎main‎ > ‎

oracle is bad

How To Handle Exceptions In Servlets

Date: 10/02/2004

This document will help you understand: 
• How to handle servlet exceptions using different techniques that suit the application
• How to run the sample servlet applications

Table of Contents

Introduction 
Prerequisites 
Software Requirements 
How to Handle Servlet Exceptions?
Running the Sample Servlet Applications
Useful References
Troubleshooting

Introduction

Servlets provide a component-based platform-independent method for building web-based applications, and are generally used to generate dynamic web content. To put it simply, a servlet receives a request from a client (the web browser, for instance), processes the request, and returns the response to the client. For example, the response can be some content queried from a database that is displayed using HTML.

For more information about Servlets, refer to the Useful References section later in this document.

What are Servlet exceptions?

Servlet exceptions are generally abnormal conditions that can occur while executing a piece of code in a servlet. Exceptions can occur at run-time(for instance, when a servlet is processing the form data) or at compile-time. Exceptions need to be handled properly, otherwise the application may not be as good functionally. Some of the common exceptions encountered in a servlet are the HTTP Servlet errors like Internal server errors 500, 404 etc.., the data handling errors likeNumberFormatError, NullPointerException, DivideByZeroException etc.. Compile-time exceptions need to be handled before launching the web application into production. This document gives a detailed discussion on how to handle exceptions in servlets.

Prerequisites

To work your way through this HowTo, it is necessary to have a basic understanding of the fundamental concepts of servlets, and how to develop and deploy them to a web server. You may also want to know about the fundamentals of JSP which work closely with servlets. You can always read the extensive information (in the form of tutorials, articles or HowTo's) about servlets and JSPs, on Sun and OTN sites.

Software Requirements

  • Oracle JDeveloper 10g or later ( JDeveloper is Oracle's Visual Java Development Tool and can be downloaded from here. )
  • OR
    Oracle Application Server Containers for J2EE(OC4J) 9.0.3 or later (Download from here. ) 
  • JDK1.3.x or later. (Download from here. )

How to handle servlet exceptions

In a Java servlet, an exception is represented by an instance of the class -javax.servlet.ServletException. There are many ways of handling exceptions in a servlet. Following is the listing of different techniques. Click on the each of the link to know more about them.

  1. Using the web.xml file to handle exceptions and errors declaratively
  2. Using a RequestDispatcher to forward the request to an error page
  3. Using the HttpServletResponse method sendError()
  4. Using the Web Application Log to record the exception messages
  5. Using the HttpServletResponse method setStatus to return the error state to the browser
  6. Accessing the error attributes from HttpServletRequest object

Following is a pictorial representation of different exception handling techniques in a servlet:

1. Using the web.xml file to handle exceptions and errors declaratively

Handling errors in a web application can be defined declaratively using the sub elements of <error-page> element in the WEB-INF/web.xml file.

  • If the servlet chooses to handle the error codes, <error-code> element that is within <error-page> element is used to identify the value.
  • If, however, the page chooses to handle an exception, <exception-type> tag that is within <error-page> element is used. 

Following is a code snippet that demonstrates handling of Internal server 500 error in a servlet. Whenever this exception is encountered, the JSP or servlet mapped in <location> tag is displayed. In the example, the web.xml file has mapped 500error.html page for handling Internal server 500 error. The file 500error.html can be a simple HTML page that displays a customized message for the exception.

Servlet code snippet for handling error-code:

public void service(HttpServletRequest request, 
HttpServletResponse response)
throws ServletException, IOException {
try {
// Erroneous code that results in 'Divide by Zero' Exception invariably.
// This is caught by a generic Exception.
int test = 1/0;
} catch (Exception e) {
// The above code leads to Internal Server error 500. This is mapped
// to 500error.html in web.xml. When this Servlet is requested,
// customized page is displayed.
throw new ServletException("Servlet caught a ServletException: "
+ e.getMessage());
}
}

The web.xml mapping for handling error-code:

<web-app>
.......
<error-page>
<error-code>500</error-code>
<location>/500error.html</location>
</error-page>

........
</web-app>

Servlet handling Exception-type:

Following is an example of handling the exception-type: NumberFormatException declaratively in the web.xml file. Whenever this exception is encountered, the JSP or servlet mapped in <location> tag is displayed. In the example, web.xml has mapped error.jsp page for handling the exception of the type java.lang.NumberFormatException, using <exception-type> tag. The error.jsp file can be a customized Error JSP that displays the exception message using the implicit object method- exception.getMessage()

  public void service(HttpServletRequest request, 
HttpServletResponse response)
throws ServletException, IOException {
// The following piece of code results in NumberFormatException that will
// be detected by the application server. The configured file error.jsp is
// displayed whenever NumberFormatException is encountered. Look up the
// deployment descriptor web.xml file for more details.
try {
// Erroneous code that results in NumberFormatException invariably.
int test = Integer.parseInt("abc");
} catch (NumberFormatException nfe) {
// throw the exception defined in web.xml to display corresponding file.
throw new NumberFormatException("Servlet caught a NumberFormatException: "
+ nfe.getMessage()
);
}
}

Customized error.jsp listing:

<%@ page contentType="text/html"%>
<%@ page language="java"%>
<%@ page isErrorPage="true" %>
<html>
<head>
<title>Custom Error Page for CreateExceptionServlet</title>
</head>
<body><b><FONT face="Verdana, Arial,Helvetica, sans-serif"
size="2" color="#009999" align="left">
This is an error JSP!! Look at the error message below:<BR>
<%=exception.getMessage() %>
</font></b>
</body>
</html>

The web.xml mapping for handling exception-type:

<web-app>
.......
<error-page>
<exception-type>java.lang.NumberFormatException</exception-type>
<location>/error.jsp</location>
</error-page>

........
</web-app>

2. Using a RequestDispatcher to forward the request to an error page

A RequestDispatcher can be used to receive the requests from the client and forward the same to any resource such as a servlet, HTML file, or JSP file on the server. This mechanism can be made use of to forward the request to a different resource whenever an exception is encountered. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.

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

// The following piece of code results in NumberFormatException which will
// be detected by the container. The RequestDispatcher object will forward
// the same request to the other resource, here the file: forwardedJSP.jsp
try {
int test = Integer.parseInt("abc");
} catch (NumberFormatException nfe) {
RequestDispatcher rd = request.getRequestDispatcher("/forwardedJSP.jsp");
rd.forward(request, response);
} }

3. Using the HttpServletResponse method sendError()

The sendError() method will cause the servlet container to send an error page to the browser. The string message that can be set in sendError()is ignored if the error code has a mapping file configured in web.xml. Otherwise it will be displayed in the browser.

In the following example, the error 300 indicated by SC_MULTIPLE_CHOICES is mapped to the file 300error.html in the file web.xml

 public void doGet(HttpServletRequest request, 
HttpServletResponse response)
throws ServletException, IOException {
String mg ="This message is not displayed if error page is "+
"configured in web.xml";
response.sendError(response.SC_MULTIPLE_CHOICES, mg); }

Example 300error.html page:


<HTML>
<TITLE>Custom Error page for SendError300 Servlet</TITLE>
<BODY><b><FONT face="Verdana, Arial,Helvetica, sans-serif"
size="2" color="#009999" align="left">
<P>This is a customized message for Internal Server Error 300 Page.</P>
<P>Check your Servlet!!</P></font></b>
</BODY>
</HTML>

The web.xml mapping:


<web-app>
.......
<error-page>
<error-code>300</error-code>
<location>/300error.html</location>
</error-page>
.......
</web-app>

4. Using Web Application Log to record the exception messages

The exception event can be logged in an application log file. The log() methods are available in GenericServlet and ServletContext objects. It is seen that the log() method provided by the GenericServlet methods prepend the servlet name to the message while the ServletContext methods do not.

Following is a code snippet to log the exception and a corresponding message to the application log file. The location of the log file is specific in thevendor specific application.xml file. For example, for OC4J, it is configured in the orion-application.xml file.

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

// The following piece of code results in NumberFormatException that will
// be detected by the application server. The exception and the message is
// logged in the application log file specified in the vendor specific
// application.xml file. In case of OC4J, it is orion-application.xml file.

try {
// Erroneous code that results in NumberFormatException invariably.
int test = Integer.parseInt("abc");
} catch (NumberFormatException nfe) {

// log the exception message in the application log file.
getServletContext().log("Servlet caught a NumberFormatException: "
+ nfe.getMessage());
} }

Example orion-application.xml file entry for the log file location

<orion-application>
<log>
<file path="application.log" />
</log>
</orion-application>

 

Sample application.log file entry for the exception:

03/11/18 16:55:24 exceptions: JDevOJSP: init
03/11/18 16:55:24 exceptions: 9.0.4.0.0 Started
03/11/18 16:55:24 exceptions: CreateExceptionServlet: init
03/11/18 16:55:24 exceptions: Servlet caught a
NumberFormatException: For input string: "abc"

 

5. Using the HttpServletResponse method setStatus to return the error state to the browser

The servlet can use the status codes to indicate the status of the response. This method does not trigger the container to generate an error page. It just sends the status code to the browser. The setStatus() method sets the status code(integer) and the servlet code continues to process. A call to this method is ignored if the response is already committed. Default status code is 200 (OK). 

The status codes fall into five general categories:

  • 100-199 Informational.
  • 200-299 Successful.
  • 300-399 Redirection.
  • 400-499 Incomplete.
  • 500-599 Server Error.

Following is a code snippet to use the setStatus() method.

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

// Set the status response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
// Forward the request to a different location
response.setHeader("Location", ""http://www.oracle.com");
}

6. Accessing error attributes from HttpServletRequest object

When the Web container receives or generates an exception or system error, it initializes several variables as request attributes. Following is a sample code to get the values of these attributes in a servlet. For example, these values can be used to create a customized error servlet.

...........

protected static String[] vars = {
"javax.servlet.error.status_code",
"javax.servlet.error.exception_type",
"javax.servlet.error.message",
"javax.servlet.error.exception",
"javax.servlet.error.request_uri"

};

public void service(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out = response.getWriter();
out.println("<HTML><BODY><TABLE>");
// Print the attributes
for (int i = 0; i < vars.length; i++) {
out.println("<TR><TD>" + vars[i] + "</TD><TD>"+
request.getAttribute(vars[i]) +
"</TD></TR>");
}
out.println("</TABLE></BODY></HTML>");
}
..........

Running the sample servlet applications

This section talks about how to get the servlets up and running. The application downloadable Jar file has a set of six servlet applications which demonstrate different servlet exception handling techniques.

    The sample application HandlingServletExceptions.jar can be downloaded from here. The Jar file extracts all the sample application files to a folder calledHandlingServletExceptions. Go through the following steps to deploy and run the servlets in OC4J: 

    1. Add servlet.jar to the CLASSPATH; this file is present under <OC4J_HOME>/j2ee/home/lib folder.
      Note: <OC4J_HOME> is the folder where you have installed the OC4J server; For example, d:\oc4j
    2. From the HandlingServletExceptions folder, compile the servlet files: CatchError500.java, CreateExceptionServlet.java, SendError300.java, SetStatusServlet.java, UsingRequestDispatcher.java, UsingErrorServlet.java using the following command:
      javac src/oracle/otnsamples/servlets/*.java -d ./WEB-INF/classes
      - This creates the classes for the servlet files under the WEB-INF/classes/oracle/otnsamples/servlets folder. 
    3. Next, create a WAR file containing all the servlet classes, JSPs, HTML files and the web.xml file using the JAR command: 
      jar -cvfM exceptions.war WEB-INF/* web/*.jsp web/*.html

    4. Create a EAR file containg the application.xml file and WAR file using the JAR command again.
      jar -cvfM exceptions.ear exceptions.war META-INF
    5. Start the OC4J server.
    6. Copy the EAR file: exceptions.ear to the <OC4J_HOME>/j2ee/home/applications folder.
    7. Deploy the servlet applications using the command below:

      java -jar <OC4J_HOME>/j2ee/home/admin.jar ormi://<server>:<rmiport> admin <admin_password> -deploy -file <Sample_Name>.ear -deploymentName <earDeploymentName>

      Example:
      java -jar D:/oc4j10g/j2ee/home/admin.jar ormi://incq207a.idc.oracle.com:23791 admin welcome -deploy -file exceptions.ear -deploymentName exceptions

      Note: 
      <server> is the IP Address of the system where the OC4J instance is running.
      <rmiport> is the RMI port number of the OC4J instance; default is 23791
      <admin_password> is the password of the OC4J installation
      <Sample_Name>.ear is the EAR file created, that is, exceptions.ear
      <earDeploymentName> is the deployment name for the application, that is, exceptions

    8. Bind the web application to a context root using the following command:

      java -jar <OC4J_HOME>/j2ee/home/admin.jar ormi://<server>:<rmiport> <admin_username> <admin_password> -bindWebApp <earDeploymentName> <Sample_War_Name> http-web-site /<website_root>

      Example: java -jar D:/oc4j10g/j2ee/home/admin.jar ormi://incq207a.idc.oracle.com:23791 admin welcome -bindWebApp exceptions exceptions http-web-site /exceptions 

    9. Access the servlets using the URLs like the following:

      http://localhost:8888/exceptions/servlet/CatchError500
      http://localhost:8888/exceptions/servlet/CreateExceptionServlet
      http://localhost:8888/exceptions/servlet/SendError300
      http://localhost:8888/exceptions/servlet/SetStatusServlet
      http://localhost:8888/exceptions/servlet/UsingRequestDispatcher
      http://localhost:8888/exceptions/servlet/UsingErrorServlet
    10. Where localhost is your machine where OC4J instance is running. 8888 is the default port of OC4J.

    11. Each of the servlet thus invoked simulate different servlet exceptions, and demonstrate an exception handling technique.
       

Running the Servlet from Oracle JDeveloper 10g:

    The sample application HandlingServletExceptions.jar can be downloaded from here. The jar file extracts all the sample application files to a folder calledHandlingServletExceptions. Go through the following steps to run the servlet from JDeveloper.

    1. From JDeveloper, open the  HandlingServletExceptions.jws workspace file. This will open the corresponding project and source files of the application.
    2. Compile the HandlingServletExceptions.jpr project.
    3. Click on CatchError500.java and run the servlet. Similarly, you can run other servlets - CatchError500, CreateExceptionServlet, SendEError300, SetStatusServlet, UsingRequestDispatcher, UsingErrorServlet.
    4. Each of the servlet thus invoked simulate different exceptions, and demonstrate an exception handling technique.

Useful References

Troubleshooting

Back To Top
  • Its possible that from the Microsoft Internet Explorer, you may not be able to see some of the customized error pages that are configured in web.xml. Instead you will see 'Page Not Found' - 404 error. To rectify this problem, from the browser's 'Tools' main menu , choose the option 'Internet Options'. Click on the 'Advanced' tab. Uncheck the option 'Show friendly HTTP error messages' and try invoking the servlets again.

Do enter your comments about this HowTo in the OTN Sample Code Discussion Forum.

Comments