Java The Servlet Container Model

The Servlet Container Model


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 [email protected]
 */

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.

Latest Posts

Related Stories