September 17, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

The Servlet Container Model

  • October 24, 2002
  • By Que Publishing
  • Send Email »
  • More Articles »

This is Chapter 4: Servlet Container Model from the book Sun Certification Training Guide (310-080): Java 2 Enterprise Edition (J2EE) Web Component Developer (ISBN:0-7897-2821-4) written by Alain Trottier, published by Que.


Chapter 4: Servlet Container Model

Chapter 4: Servlet Container Model

Objectives

This chapter covers the following objectives listed by Sun in "Section 1—The Servlet Model" and "Section 3—The Servlet Container Model."

1.1 For each of the HTTP methods, GET, POST, and PUT, identify the corresponding method in the HttpServlet class.

The HTTP methods GET, POST, and PUT are how browsers and Web servers communicate the purpose of communication. A GET simply wants to retrieve a page without providing much information. A POST, however, can package lots of form or file information with its request. A PUT is for uploading a file. The HttpServlet class has a corresponding method for each HTTP method, including doGet(), doPost(), and doPut().

1.2 For each of the HTTP methods, GET, POST, and HEAD, identify triggers that might cause a browser to use the method, and identify benefits or functionality of the method.

This objective asks you to understand the events associated with each type of request. For example, clicking a hyperlink will send a GET request to a Web server, but clicking a Submit button (when the action is set to "post") will send a POST request.

1.3 For each of the following operations, identify the interface and method name that should be used to

  • Retrieve HTML form parameters from the request
  • Retrieve a servlet initialization parameter
  • Retrieve HTTP request header information
  • Set an HTTP response header; set the content type of the response
  • Acquire a text stream for the response
  • Acquire a binary stream for the response
  • Redirect an HTTP request to another URL

    This objective is huge. It encompasses the heart of a servlet process, especially the request and response objects. The request parameters for the servlet are the strings sent by the client to the Servlet Container. The container parses the request and puts the information in an HttpServletRequest object which is passed to the servlet. Going the other way, the container wraps the response parameters in an HttpServletResponse object which is passed back to the container. The associated chapter section later in this chapter ("Overriding HttpServlet GET, POST, and PUT methods") goes into much detail on the methods involved.

1.4 Identify the interface and method to access values and resources and to set object attributes within the following three Web scopes:

  • Request
  • Session
  • Context

    This objective addresses the idea of scope. When something has Context scope, it is application-wide and all users can share data. Session scope means one user can share data across page views, but other users can't. Request scope restricts data to only that page.

1.5 Given a life-cycle method, identify correct statements about its purpose or about how and when it is invoked. These methods are

  • init
  • service
  • destroy

    The container manages the servlet life-cycle. This part of the chapter explains, with examples, how the container initializes a servlet with a call to the init() method. Then it calls the service() method upon every request. Finally, when the servlet is about to be removed from memory, the container calls its destroy() method. This gives the servlet one last chance to clean up resources.

1.6 Use a RequestDispatcher to include or forward to a Web resource.

The RequestDispatcher object is the servlet forwarding mechanism. You will see in the section "Servlet Life-cycle" how you can transfer processing of the request from one servlet to another (which the browser will be unaware of). This is how a servlet can pass the request to some other Web component within the same Web container.

3.1 Identify the uses for and the interfaces (or classes) and methods to achieve the following features:

  • Servlet context initialization parameters
  • Servlet context listener
  • Servlet context attribute listener
  • Session attribute listeners

    These elements let you get and monitor servlet attributes. Not only can you get them and change them too, but you can actually put in place behavior to occur when an attribute changes. The listeners are event-driven triggers. When an attribute changes, special targeted methods are called. In them, you can define special actions, such as adding a note to the log every time the user count changes (perhaps a context attribute called counter).

3.3 Distinguish the behavior of the following in a distributable:

  • Servlet context initialization parameters
  • Servlet context listener
  • Servlet context attribute listener
  • Session attribute listeners

    As explained in the previous objective, these elements let you get and monitor Servlet attributes. There is a difference here in that Sun wants you to understand how this works in a distributable Web application.

Outline

Introduction

Overriding HttpServlet GET, POST, and PUT Methods

GET

POST

PUT

Triggering HttpServlet GET, POST, and PUT Methods

GET

POST

HEAD

Interfacing with HTML Requests

Form Parameters

Retrieving a Servlet Initialization Parameter

Retrieving HTTP Request Header Information

Acquiring a Binary Stream for the Response

Redirecting an HTTP Request to Another URL

Web Application Scope

Request

Session

Context

Servlet Life-cycle

Using a RequestDispatcher

Web Application Context

Context Within a Distributable Web Application

The key to this section of the exam is understanding how servlets implement the Servlet interface, which defines life-cycle methods. The Servlet Container (such as Apache Tomcat) is itself an application that monitors a port on a given IP address. Servlets generate responses to HTTP requests. To do so, the container loads your servlet (if it isn't in memory already) and calls the methods defined in the interface. This is the foundation of servlet and JSP architecture.

There are many methods to know. It is easier if you learn the methods in groups according to theme. For example, write a servlet that has HttpServlet methods which handle all three GET, POST, and PUT types of request.

Each JavaServer Page is transformed into a servlet that is compiled and then loaded. Therefore much of what you learn here applies to the JSP section of the exam too.

Introduction

JSP and servlets have greatly enhanced the way in which you can create and manage Web pages. The difficulty level of coding JSP is between that of coding HTML and pure Java. Servlets are pure Java. The idea behind having both is providing a way for non-programmers to contribute functionality through JSP. You can "program" a JSP page almost as easily as you can write an HTML page. For simple tasks like displaying the current date, you write a normal HTML page and add only a small amount of Java as a scriptlet. For big tasks like processing a shopping cart, you use JSP as the mediator between the Web form and a component(s) (bean or servlet) that has all the horsepower. Most of the code in a Web application will go into servlets. The JSP portion is a soft front end to the application that, typically, marketing can use comfortably.

There is a lot that happens when a servlet is invoked. This chapter covers much material that explains each step of the process. At this point, it will help to provide an overview of what happens in a typical JSP/servlet request. The sequence of events starts with a browser sending a request to a Web server. The server hands the request to a Servlet Container. The container loads the servlet (if it isn't already loaded), instantiates a request and response objects, and then hands these objects to the servlet by calling first its init() method, then its service() method, and lastly the destroy() method. The service() method will typically call one of the doXXX() methods such as doGet().

All these steps are covered in detail later in this chapter. Presently, just review the overall process presented in Figure 4.1.

Let's study an example of a servlet. The following is a fully functioning, albeit trivial, servlet example. Listing 4.1 represents all that is required to have a complete servlet.

Figure 4.1
Servlet handling of an HTTP Request.

Listing 4.1 The Source Code of a Minimum Servlet

/* SimpleServletExample.java, v 1.0
 *
 */

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * A simple servlet.
 * SCWCD Exam Objective 1.1 = doGet(), doPost(), doPut()
 *
 * @author Reader@Que
 */

public class SimpleServletExample extends HttpServlet 
{
  // doGet() - SCWCD Exam Objective 1.1
  public void doGet(HttpServletRequest request,
           HttpServletResponse response)
    throws IOException, ServletException
  {
    // set the MIME type
    response.setContentType("text/html");

    // use this to print to browser
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title> A simple servlet. </title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Simple Servlet</h1>");
    out.println("This is a trivial " +
          "example of a servlet.");
    out.println("</body>");
    out.println("</html>");
  }
}

Listing 4.1 showed you an example of a servlet. The code is ordinary, but notice one small thing about printing to the browser. This example uses PrintWriter instead of using ServletOutputStream. The former is used for text, while the latter is used for bytes. See Figure 4.2 for a picture of the output. Listing 4.2 is the HTML the servlet generates and sends to the browser.

Listing 4.2 The Source Code Returned to the Browser by Listing 4.1

<html>
<head>
<title> A simple servlet. </title>
</head>
<body>
<h1>Simple Servlet</h1>
This is a trivial example of a servlet.
</body>
</html>

The HTML in Listing 4.2 is rendered by a browser so that it looks like Figure 4.2.

Figure 4.2
You can create dynamic content using a servlet.


How Does a Servlet Work?

You write a servlet and compile it, and then place it in the appropriate directory. When the Servlet Container starts, it will preload your servlet in memory if specified in the web.xml configuration file. If your servlet is not already loaded (not listed in the web.xml configuration file), its instance will be created as soon as a request for it is received by the Servlet Container. The first time it is loaded, the container calls your servlet's init() method, if there is one. Notice that it gets called only once, so place one-off functionality in this method (such as database connection, file object). Now that your servlet is ready, it waits for requests. The container will call your service() method each time a request is received for your servlet. The HttpServlet class (which your servlet must extend) already has this method, so you don't have to write one, but you can override it. The service() method then passes the request on to the appropriate method (usually GET for simple requests and POST to submit data, say a Web page form) such as the doGet() method if it is a GET request, or the doPost() method if it is a POST request. The doXXX() methods are the ones you need to override and where you will spend most of your effort. The servlet processes the request (code you write in doGet()), returning a response to the container. The container sends the text of the response back to the browser.

The preceding JSP and servlet examples are part of a Web application. A Web application is a collection of servlets, JSP pages, HTML documents, and other Web resources (such as image files, compressed archives, and other data). This collection may be packaged into an archive or exist as separate files in an open directory structure. Since you have many servlet classes, JSP pages, HTML pages, and other supporting libraries and files for a given Web application, there are many dependencies. These are not trivial to manage. It is vital that all parts go in their correct locations in the Web application archive or in an open directory structure. Once you get the dependencies resolved, it is a good idea to package the collection into a Web application archive, a single file with the .war extension that contains all of the components of a Web application. You can do this using standard JAR tools.

Now, we need to define what is meant regarding deploying a Web application. Normally, Web applications run on only one VM at any one time. When we talk about deploying a Web application, we mean that the collection of files that comprise a Web application is placed into a Web server's runtime (at least one part goes into JVM, which can then link to or grab other parts). What happens if you want to deploy your Web application in a Web farm? In this case, your Web application will run on several VMs simultaneously.

A distributable Web application is written so that it can be deployed in a Web container, distributed across multiple Java virtual machines running on the same host or different hosts. The two keys to making this possible are how you thread the servlets and what you tell the deployment descriptor. With the right combination of these, your Web application will run on several VMs simultaneously. The servlet declaration, which is part of the deployment descriptor, controls how the Servlet Container provides instances of the servlet. Normally, the Servlet Container uses only one instance per servlet declaration. However, for a servlet implementing the SingleThreadModel interface, the Servlet Container may instantiate multiple instances to handle a heavy request load and serialize requests to a particular instance.

In the case where a servlet is marked in the deployment descriptor as distributable and the application implements the SingleThreadModel interface, the container may instantiate multiple instances of that servlet in each VM of the container or across many machines (clustering servlets usually through serialization). The container has a complicated task in managing requests, sessions, and contexts across JVMs. How each vendor accomplishes this is beyond the scope of this book. You do need to know that to convert your Web application into a distributable one, you must implement the SingleThreadModel interface and mark the servlet as distributable in the deployment descriptor (see Chapter 10, "Web Applications," for more about web.xml).


Overriding HttpServlet GET, POST, and PUT Methods

1.1 For each of the HTTP methods, GET, POST, and PUT, identify the corresponding method in the HttpServlet class.

GET

POST

PUT

This exam objective addresses the most-used feature of servlets, namely, responding to HTTP requests. The exam will have several questions on this topic. These three types of requests dominate browser-server traffic.

The following code is a minimal template showing you how to use the GET, POST, and PUT methods. GET appends data to the URL before the URL is submitted to the server, whereas POST sends the data to the server separately from the URL. GET submissions can only be 1KB in length in most cases, whereas POST submissions can be arbitrarily large. The results of a GET submission can be reliably bookmarked, whereas the results of a POST submission can't. There are several differences between them which are explained later in this section.

These methods are called by the service method (not required in your servlet as it is in HttpServlet, as this method is inherited from HttpServlet). Together they can look like Listing 4.3.

Listing 4.4 Servlet That Handles GET, POST, and PUT Requests

/* doGetdoPostdoPutServlet.java, v 1.0
* SCWCD Exam Objective 1.1 = doGet(), doPost(), doPut()
 *
 */

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * A servlet that reports back to the browser
 * the type of request received.
 *
 * @author Reader@Que
 */

public class doGetdoPostdoPutServlet extends HttpServlet 
{
  // doGet() - SCWCD Exam Objective 1.1
  public void doGet(HttpServletRequest request,
           HttpServletResponse response)
    throws IOException, ServletException
  {
    reportType("doGet", response);
  }
  
  // doPost() - SCWCD Exam Objective 1.1
  public void doPost(HttpServletRequest request,
           HttpServletResponse response)
    throws IOException, ServletException
  {
    reportType("doPost", response);
  }
  
  // doPut() - SCWCD Exam Objective 1.1
  public void doPut(HttpServletRequest request,
           HttpServletResponse response) 
    throws IOException, ServletException
  {
    reportType("doPut", response);
  }
  
  public void reportType(String requestType, 
              HttpServletResponse response)
    throws IOException, ServletException
  {
    // set the MIME type
    response.setContentType("text/html");

    // use this to print to browser
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>doGetdoPostdoPutServlet" +
           "</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Your Request</h1>");
    out.println("Your request type: " + requestType);
    out.println("</body>");
    out.println("</html>");
  }
} 

Listing 4.3 sends a basic HTML message back to the browser that looks like Figure 4.3.

Figure 4.3
Filtering request types using a servlet.

It is the service method that calls the doXXX() methods. While you normally wouldn't override the service method, Listing 4.4 presents a skeleton example of what you could do with it. You might want to preprocess the request before sending it on to the appropriate doXXX() method.

Listing 4.4 Service Method Example

protected void service(HttpServletRequest req, 
            HttpServletResponse resp)
  throws ServletException, IOException
{
   String method = req.getMethod();

   if (method.equals(METHOD_GET)) 
   {
     doGet(req, resp);
   } else if (method.equals(METHOD_POST)) 
   {
     doPost(req, resp);
   } else if (method.equals(METHOD_PUT)) 
   {
     doPut(req, resp);
   } else 
   {
    // Servlet doesn't currently support 
    // other types of request.
    String errMsg = "Method Not Supported");
    resp.sendError(
      HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
   }
}

GET

The GET type request is normally used for simple HTML page requests. It has this syntax:

  public void doGet(HttpServletRequest request,
           HttpServletResponse response)
    throws IOException, ServletException
    { //your code here}

When you write a servlet, this is the one method that you will start with. If this method is all you had in your servlet, it would handle the majority of your Web server's needs regarding this servlet. Notice, that the init() and service() methods involved in a request are already provided by the HttpServlet class, so they don't need to be overridden, although you can do so.





Page 1 of 5



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel