[ Team LiB ] Previous Section Next Section

Recipe 1.1 Writing a Servlet

Problem

You want to write a servlet that is part of a web application.

Solution

Create a Java class that extends javax.servlet.http.HttpServlet. Make sure to import the classes from servlet.jar (or servlet-api.jar)—you'll need them to compile the servlet.

Discussion

A servlet is a Java class that is designed to respond with dynamic content to client requests over a network. If you are familiar with Common Gateway Interface (CGI) programs, then servlets are a Java technology that can replace CGI programs. Often called a web component (along with JSPs), a servlet is executed within a runtime environment provided by a servlet container or web container such as Jakarta Tomcat or BEA WebLogic.

A web container can be an add-on component to an HTTP server, or it can be a standalone server such as Tomcat, which is capable of managing HTTP requests for both static content (HTML files) as well as for servlets and JSPs.


Servlets are installed in web containers as part of web applications. These applications are collections of web resources such as HTML pages, images, multimedia content, servlets, JavaServer Pages, XML configuration files, Java support classes, and Java support libraries. When a web application is deployed in a web container, the container creates and loads instances of the Java servlet class into its Java Virtual Machine (JVM) to handle requests for the servlet.

A servlet handles each request as a separate thread. Therefore, servlet developers have to consider whether to synchronize access to instance variables, class variables, or shared resources such as a database connection, depending on how these resources are used.


All servlets implement the javax.servlet.Servlet interface. Web application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is specially designed to handle HTTP requests.

The following basic sequence occurs when the web container creates a servlet instance:

  1. The servlet container calls the servlet's init( ) method, which is designed to initialize resources that the servlet might use, such as a logger (see Chapter 14). The init( ) method gets called only once during the servlet's lifetime.

  2. The init( ) method initializes an object that implements the javax.servlet.ServletConfig interface. This object gives the servlet access to initialization parameters declared in the deployment descriptor (see Recipe 1.5). ServletConfig also gives the servlet access to a javax.servlet.ServletContext object, with which the servlet can log messages, dispatch requests to other web components, and get access to other web resources in the same application (see Recipe 13.5).

Servlet developers are not required to implement the init( ) method in their HttpServlet subclasses.


  1. The servlet container calls the servlet's service( ) method in response to servlet requests. In terms of HttpServlets, service( ) automatically calls the appropriate HTTP method to handle the request by calling (generally) the servlet's doGet( ) or doPost( ) methods. For example, the servlet responds to a user sending a POST HTTP request with a doPost( ) method execution.

  2. When calling the two principal HttpServlet methods, doGet( ) or doPost( ), the servlet container creates javax.servlet.http.HttpServletRequest and HttpServletResponse objects and passes them in as parameters to these request handler methods. HttpServletRequest represents the request; HttpServletResponse encapsulates the servlet's response to the request.

Example 1-1 shows the typical uses of the request and response objects. It is a good idea to read the servlet API documentation (at http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/package-summary.html), as many of the method names (e.g., request.getContextPath( )) are self-explanatory.


  1. The servlet or web container, not the developer, manages the servlet's lifecycle, or how long an instance of the servlet exists in the JVM to handle requests. When the servlet container is set to remove the servlet from service, it calls the servlet's destroy( ) method, in which the servlet can release any resources, such as a database connection.

Example 1-1 shows a typical servlet idiom for handling an HTML form. The doGet( ) method displays the form itself. The doPost( ) method handles the submitted form data, since in doGet( ), the HTML form tag specifies the servlet's own address as the target for the form data.

The servlet (named FirstServlet) specifies that the declared class is part of the com.jspservletcookbook package. It is important to create packages for your servlets and utility classes, and then to store your classes in a directory structure beneath WEB-INF that matches these package names.

The FirstServlet class imports the necessary classes for compiling a basic servlet, which are the emphasized import statements in Example 1-1. The Java class extends HttpServlet. The only defined methods are doGet( ) , which displays the HTML form in response to a GET HTTP request, and doPost( ), which handles the posted data.

Example 1-1. A typical HttpServlet used for handling an HTML form
package com.jspservletcookbook;    

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

import java.util.Enumeration;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FirstServlet extends HttpServlet {
    
  public void doGet(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException,
      java.io.IOException {
    
    //set the MIME type of the response, "text/html"
    response.setContentType("text/html");
    
    //use a PrintWriter to send text data to the client who has requested the
    //servlet
    java.io.PrintWriter out = response.getWriter( );

    //Begin assembling the HTML content
    out.println("<html><head>");
    
    out.println("<title>Help Page</title></head><body>");
    out.println("<h2>Please submit your information</h2>");
   
   //make sure method="post" so that the servlet service method
   //calls doPost in the response to this form submit
    out.println(
        "<form method=\"post\" action =\"" + request.getContextPath( ) +
            "/firstservlet\" >");

    out.println("<table border=\"0\"><tr><td valign=\"top\">");
    out.println("Your first name: </td>  <td valign=\"top\">");
    out.println("<input type=\"text\" name=\"firstname\" size=\"20\">");
    out.println("</td></tr><tr><td valign=\"top\">");
    out.println("Your last name: </td>  <td valign=\"top\">");
    out.println("<input type=\"text\" name=\"lastname\" size=\"20\">");
    out.println("</td></tr><tr><td valign=\"top\">");
    out.println("Your email: </td>  <td valign=\"top\">");
    out.println("<input type=\"text\" name=\"email\" size=\"20\">");
    out.println("</td></tr><tr><td valign=\"top\">");

    out.println("<input type=\"submit\" value=\"Submit Info\"></td></tr>");
    out.println("</table></form>");
    out.println("</body></html>");

    }//doGet
  public void doPost(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException,
    java.io.IOException {
    
    //display the parameter names and values
    Enumeration paramNames = request.getParameterNames( );

    String parName;//this will hold the name of the parameter
    
    boolean emptyEnum = false;

    if (! paramNames.hasMoreElements( ))
        emptyEnum = true;
    
        
    //set the MIME type of the response, "text/html"
    response.setContentType("text/html");
    
    //use a PrintWriter to send text data to the client 
    java.io.PrintWriter out = response.getWriter( );
    
    //Begin assembling the HTML content
    out.println("<html><head>");
    out.println("<title>Submitted Parameters</title></head><body>");
    
    if (emptyEnum){
        out.println(
           "<h2>Sorry, the request does not contain any parameters</h2>");
    } else {
    out.println(
        "<h2>Here are the submitted parameter values</h2>");
    }
    
    while(paramNames.hasMoreElements( )){
    
        parName = (String) paramNames.nextElement( );

        out.println(
            "<strong>" + parName + "</strong> : " +
                request.getParameter(parName));

        out.println("<br />");

    }//while
        
    out.println("</body></html>");
    
  }// doPost
}

You might have noticed that doGet( ) and doPost( ) each throw ServletException and IOException. The servlet throws IOException because the response.getWriter( ) (as well as PrintWriter.close( )) method call can throw an IOException. The doPost( ) and doGet( ) methods can throw a ServletException to indicate that a problem occurred when handling the request. For example, if the servlet detected a security violation or some other request problem, then it could include the following code within doGet( ) or doPost( ):

//detects a problem that prevents proper request handling...
throw new ServletException("The servlet cannot handle this request.");

Figure 1-1 shows the output displayed by the servlet's doGet( ) method in a browser.

Figure 1-1. The servlet's output for doGet( ) method
figs/jsjc_0101.gif

Figure 1-2 shows the servlet's output for the doPost( ) method.

Figure 1-2. The servlet's output for the doPost( ) method
figs/jsjc_0102.gif

See Also

Recipe 1.3 on compiling a servlet; Recipe 1.4 on packaging servlets and JSPs; Recipe 1.5 on creating the deployment descriptor; Chapter 2 on deploying servlets and JSPs; Chapter 3 on naming servlets; the javax.servlet.http package JavaDoc: http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/package-summary.html; the J2EE tutorial from Sun Microsystems: http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/J2eeTutorialTOC.html; Jason Hunter's Java Servlet Programming (O'Reilly).

    [ Team LiB ] Previous Section Next Section