Section 1 - The Servlet Model

 

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

 

HttpServlet

Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:

There's almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above).

Likewise, there's almost no reason to override the doOptions and doTrace methods.

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.

 

A browser may make a HEAD request for any page it has in cache.  It uses the results of the request to determine if it can reload the requested page from cache or reload it from the server.  It uses the Last-Modified date,  size and cache setting in the HEADER returned to perform this determination.

 

A GET request can be a URI, complete with path parameters (example: for URI Session tracking), UserInfo (for authentication) and query, entered by the user in the browsers Address or Location textbox.  A get request can be initiated by the user clicking on a link on an HTML page where the URI for the link can contain the required information.  A GET request can be initiated by clicking on a submit button for a form who’s action is set to GET.   GET requests provide a quick way to pass information to a server on how to fulfill a request with the need of an additional stream being established between the browser and the server.  Additional data isn’t necessary to mark the beginning or end of the data provided.  GET Requests are limited in size, usually determined by the server.  GET requests are limited to Parameter passing only. GET Parameters are visible to the user in the address textbox and can be manually manipulated.

 

A POST request is initiated by the user by clicking on submit button of a form who’s action is set to POST. POSTS are not visible in the Address textbox preventing unwanted manipulation of parameters.  POST Requests can post large number of parameters to a server.  POST can be multipart allowing additional data to be passed as well as parameters(such as file upload)

 

JavaScript can be written to simulate a user and perform a POST or GET on any event within the browser.

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

Answers

String ServletRequest.getParameter(String parameterName)  

Enumeration ServletRequest.getParameterNames()

Map ServletRequest.getParameterMap()

String[] ServletRequest.getParameterValues(String name)

String ServletConfig.getInitParameter(String parameterName)  

Enumeration ServletConfig.getInitParameterNames()

String ServletContext.getInitParameter(String parameterName)  

Enumeration ServletContext.getInitParameterNames()

String HttpServletRequest.getHeader(String name)

long HttpServletRequest.getDateHeader(String name)

int HttpServletRequest.getIntHeader(String name)

Enumeration HttpServletRequest.getHeaderNames()

Enumeration HttpServletRequest.getHeaders(String name)

void ServletResponse.setContentType(java.lang.String type)

ServletOutputStream ServletResponse.getOutputStream()

PrintWriter ServletResponse.getWriter()

void RequestDispatcher.forward(ServletRequest, ServletResponse)

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

Answers

Object ServletRequest.getAttribute(java.lang.String name)

Enumeration ServletRequest.getAttributeNames()

void ServletRequest.setAttribute(java.lang.String name, java.lang.Object o)
               

Object HttpSession.getAttribute(java.lang.String name)

Enumeration HttpSession.getAttributeNames()

void HttpSession.removeAttribute(java.lang.String name)

void HttpSession.setAttribute(java.lang.String name, java.lang.Object value)

Object ServletContext.getAttribute(java.lang.String name)

Enumeration ServletContext.getAttributeNames()

void ServletContext.removeAttribute(java.lang.String name)

void ServletContext.setAttribute(java.lang.String name, java.lang.Object object)

          

1.5 Given a life-cycle method: init, service, or destroy, identify correct statements about its purpose or about how and when it is invoked.

 

3.3 Servlet Life Cycle

A servlet is managed through a well defined life cycle that defines how it is loaded, instantiated and

initialized, handles requests from clients, and how it is taken out of service. This life cycle is

expressed in the API by the init, service, and destroy methods of the

javax.servlet.Servlet interface that all servlets must, directly or indirectly through the

GenericServlet or HttpServlet abstract classes, implement.

3.3.1 Loading and Instantiation

The servlet container is responsible for loading and instantiating a servlet. The instantiation and

loading can occur when the engine is started or it can be delayed until the container determines that

it needs the servlet to service a request.

First, a class of the servlet’s type must be located by the servlet container. If needed, the servlet

container loads a servlet using normal Java class loading facilities from a local file system, a remote

file system, or other network services.

After the container has loaded the Servlet class, it instantiates an object instance of that class for

use.

It is important to note that there can be more than one instance of a given Servlet class in the

servlet container. For example, this can occur where there was more than one servlet definition that

utilized a specific servlet class with different initialization parameters. This can also occur when a

servlet implements the SingleThreadModel interface and the container creates a pool of

servlet instances to use.

3.3.2 Initialization

After the servlet object is loaded and instantiated, the container must initialize the servlet before it

can handle requests from clients. Initialization is provided so that a servlet can read any persistent

configuration data, initialize costly resources (such as JDBC™ based connection), and perform any

other one-time activities. The container initializes the servlet by calling the init method of the

Servlet interface with a unique (per servlet definition) object implementing the

The Servlet Interface

Java™ Servlet Specification Version 2.2 21

ServletConfig interface. This configuration object allows the servlet to access name-value

initialization parameters from the servlet container’s configuration information. The configuration

object also gives the servlet access to an object implementing the ServletContext interface

which describes the runtime environment that the servlet is running within. See section 4 titled

“Servlet Context” on page 23 for more information about the ServletContext interface.

3.3.2.1 Error Conditions on Initialization

During initialization, the servlet instance can signal that it is not to be placed into active service by

throwing an UnavailableException or ServletException. If a servlet instance throws

an exception of this type, it must not be placed into active service and the instance must be

immediately released by the servlet container. The destroy method is not called in this case as

initialization was not considered to be successful.

After the instance of the failed servlet is released, a new instance may be instantiated and initialized

by the container at any time. The only exception to this rule is if the UnavailableException

thrown by the failed servlet which indicates the minimum time of unavailability. In this case, the

container must wait for the minimum time of unavailability to pass before creating and initializing a

new servlet instance.

3.3.2.2 Tool Considerations

When a tool loads and introspects a web application, it may load and introspect member classes of

the web application. This will trigger static initialization methods to be executed. Because of this

behavior, a Developer should not assume that a servlet is in an active container runtime unless the

init method of the Servlet interface is called. For example, this means that a servlet should not

try to establish connections to databases or Enterprise JavaBeans™ compenent architecture

containers when its static (class) initialization methods are invoked.

3.3.3 Request Handling

After the servlet is properly initialized, the servlet container may use it to handle requests. Each

request is represented by a request object of type ServletRequest and the servlet can create a

response to the request by using the provided object of type ServletResponse. These objects

are passed as parameters to the service method of the Servlet interface. In the case of an

HTTP request, the container must provide the request and response objects as implementations of

HttpServletRequest and HttpServletResponse.

It is important to note that a servlet instance may be created and placed into service by a servlet

container but may handle no requests during its lifetime.

3.3.3.1 Multithreading Issues

During the course of servicing requests from clients, a servlet container may send multiple requests

from multiple clients through the service method of the servlet at any one time. This means that

the Developer must take care to make sure that the servlet is properly programmed for concurrency.

If a Developer wants to prevent this default behavior, he can program the servlet to implement the

SingleThreadModel interface. Implementing this interface will guarantee that only one

request thread at a time will be allowed in the service method. A servlet container may satisfy this

guarantee by serializing requests on a servlet or by maintaining a pool of servlet instances. If the

servlet is part of an application that has been marked as distributable, the container may maintain a

pool of servlet instances in each VM that the application is distributed across.

If a Developer defines a service method (or methods such as doGet or doPost which are

dispatched to from the service method of the HttpServlet abstract class) with the

The Servlet Interface

synchronized keyword, the servlet container will, by necessity of the underlying Java runtime,

serialize requests through it. However, the container must not create an instance pool as it does for

servlets that implement the SingleThreadModel. It is strongly recommended that developers

not synchronize the service method or any of the HttpServlet service methods such as doGet,

doPost, etc.

3.3.3.2 Exceptions During Request Handling

A servlet may throw either a ServletException or an UnavailableException during

the service of a request. A ServletException signals that some error occurred during the

processing of the request and that the container should take appropriate measures to clean up the

request. An UnavailableException signals that the servlet is unable to handle requests either

temporarily or permanently.

If a permanent unavailability is indicated by the UnavailableException, the servlet

container must remove the servlet from service, call its destroy method, and release the servlet

instance.

If temporary unavailability is indicated by the UnavailableException, then the container

may choose to not route any requests through the servlet during the time period of the temporary

unavailability. Any requests refused by the container during this period must be returned with a

SERVICE_UNAVAILABLE (503) response status along with a Retry-After header indicating

when the unavailability will terminate. The container may choose to ignore the distinction between

a permanent and temporary unavailability and treat all UnavailableExceptions as

permanent, thereby removing a servlet that throws any UnavailableException from service.

3.3.3.3 Thread Safety

A Developer should note that implementations of the request and response objects are not

guaranteed to be thread safe. This means that they should only be used in the scope of the request

handling thread. References to the request and response objects should not be given to objects

executing in other threads as the behavior may be nondeterministic.

3.3.4 End of Service

The servlet container is not required to keep a servlet loaded for any period of time. A servlet

instance may be kept active in a servlet container for a period of only milliseconds, for the lifetime

of the servlet container (which could be measured in days, months, or years), or any amount of time

in between.

When the servlet container determines that a servlet should be removed from service (for example,

when a container wants to conserve memory resources, or when it itself is being shut down), it must

allow the servlet to release any resources it is using and save any persistent state. To do this the

servlet container calls the destroy method of the Servlet interface.

Before the servlet container can call the destroy method, it must allow any threads that are

currently running in the service method of the servlet to either complete, or exceed a server

defined time limit, before the container can proceed with calling the destroy method.

Once the destroy method is called on a servlet instance, the container may not route any more

requests to that particular instance of the servlet. If the container needs to enable the servlet again, it

must do so with a new instance of the servlet’s class.

After the destroy method completes, the servlet container must release the servlet instance so

that it is eligible for garbage collection

 

 

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

RequestDispatcher rd = request.getRequestDispatcher(“String path to resource”);

rd.forward(request, response);

 

or

rd.include(request, response);

 

Section 2 - The Structure and Deployment of Modern Servlet Web Applications

2.1 Identify the structure of a Web Application and Web Archive file, the name of the WebApp deployment descriptor, and the name of the directories where you place the following:

A special directory exists within the application hierarchy named “WEB-INF”. This directory

contains all things related to the application that aren’t in the document root of the application. It is

important to note that the WEB-INF node is not part of the public document tree of the application.

No file contained in the WEB-INF directory may be served directly to a client.

The contents of the WEB-INF directory are:

• /WEB-INF/web.xml deployment descriptor

• /WEB-INF/classes/* directory for servlet and utility classes. The classes in this directory

are used by the application class loader to load classes from.

• /WEB-INF/lib/*.jar area for Java ARchive files which contain servlets, beans, and other

utility classes useful to the web application. All such archive files are used by the web

application class loader to load classes from.

 

2.2 Match the name with a description of purpose or functionality, for each of the following deployment descriptor elements:

<!--

The servlet element contains the declarative data of a

servlet. If a jsp-file is specified and the load-on-startup element is

present, then the JSP should be precompiled and loaded.

-->

<!ELEMENT servlet (icon?, servlet-name, display-name?, description?,

(servlet-class|jsp-file), init-param*, load-on-startup?, security-roleref*)>

<!--

The servlet-name element contains the canonical name of the

servlet.

-->

<!ELEMENT servlet-name (#PCDATA)>

<!--

The servlet-class element contains the fully qualified class name

of the servlet.

-->

<!ELEMENT servlet-class (#PCDATA)>

<!--

The jsp-file element contains the full path to a JSP file within

the web application.

-->

<!ELEMENT jsp-file (#PCDATA)>

<!--

The init-param element contains a name/value pair as an

initialization param of the servlet

-->

<!ELEMENT init-param (param-name, param-value, description?)>

<!--

The load-on-startup element indicates that this servlet should be

loaded on the startup of the web application. The optional contents of

these element must be a positive integer indicating the order in which

the servlet should be loaded. Lower integers are loaded before higher

integers. If no value is specified, or if the value specified is not a

positive integer, the container is free to load it at any time in the

startup sequence.

-->

<!ELEMENT load-on-startup (#PCDATA)>

<!--

The servlet-mapping element defines a mapping between a servlet

and a url pattern

-->

<!ELEMENT servlet-mapping (servlet-name, url-pattern)>

Deployment Descriptor

<!--

The url-pattern element contains the url pattern of the

mapping. Must follow the rules specified in Section 10 of the Servlet

API Specification.

-->

<!ELEMENT url-pattern (#PCDATA)>