| 1.1 For each of the HTTP methods, GET, POST, and PUT, identify the corresponding method in the HttpServlet class. |
| 1.2For 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. |
1.3 For each of the following operations, identify the interface and method name that should be used:
|
1.4 Identify the interface and method to access values and resources and to set object attributes within the following three Web scopes:
|
| 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. |
| 1.6 Use a RequestDispatcher to include or forward to a Web resource. |
1.1 For each of the HTTP methods, GET, POST, and PUT, identify the corresponding method in the HttpServlet class.
J2EE Web components can be either servlets or JSP pages.
Servlets are Java programming language classes that dynamically process
requests and construct responses.
The HTTP methods are defined in the HttpServlet class. The structure is as follows:
public abstract class HttpServlet
extends GenericServlet
implements java.io.Serializable {
...
doGet
doPost
doPut
doDelete
init
destroy
getServletInfo
...
|
public abstract class GenericServlet
extends java.lang.Object
implements Servlet, ServletConfig, java.io.Serializable
|
public interface Servlet {
public void destroy()
public ServletConfig getServletConfig()
public java.lang.String getServletInfo()
public void init(ServletConfig config) throws ServletException
public void service(ServletRequest req, ServletResponse res)
throws ServletException, java.io.IOException
|
Note: ServletException is a checked exception.
Overriding this method to support a GET request also automatically supports
an HTTP HEAD request. A HEAD request is a GET request that returns no
body in the response, only the request header fields.
When overriding this method, read the request data, write the response headers,
get the response’s writer or output stream object, and finally, write the
response data. It’s best to include content type and encoding. When using a
PrintWriter object to return the response, set the content type before accessing
the PrintWriter object.
The servlet container must write the headers before committing the response,
because in HTTP the headers must be sent before the response body.
Where possible, set the Content-Length header (with the
javax.servlet.ServletResponse.setContentLength(int) method), to
allow the servlet container to use a persistent connection to return its
response to the client, improving performance. The content length is automatically
set if the entire response fits inside the response buffer.
The GET method should be safe, that is, without any side effects for which
users are held responsible. For example, most form queries have no side
effects. If a client request is intended to change stored data, the request
should use some other HTTP method.
The GET method should also be idempotent, meaning that it can be safely
repeated. Sometimes making a method safe also makes it idempotent. For
example, repeating queries is both safe and idempotent, but buying a product
online or modifying data is neither safe nor idempotent.
If the request is incorrectly formatted, doGet returns an HTTP "Bad Request"
message.
Called by the server (via the service method) to allow a servlet to handle a
GET request.
When overriding this method, read the request data, write the response headers,
get the response’s writer or output stream object, and finally, write the
response data. It’s best to include content type and encoding. When using a
PrintWriter object to return the response, set the content type before accessing
the PrintWriter object.
The servlet container must write the headers before committing the response,
because in HTTP the headers must be sent before the response body.
Where possible, set the Content-Length header (with the
javax.servlet.ServletResponse.setContentLength(int) method), to
allow the servlet container to use a persistent connection to return its
response to the client, improving performance. The content length is automatically
set if the entire response fits inside the response buffer.
When using HTTP 1.1 chunked encoding (which means that the response has
a Transfer-Encoding header), do not set the Content-Length header.
This method does not need to be either safe or idempotent. Operations
requested through POST can have side effects for which the user can be held
accountable, for example, updating stored data or buying items online.
If the HTTP POST request is incorrectly formatted, doPost returns an HTTP
"Bad Request" message.
Called by the server (via the service method) to allow a servlet to handle a
POST request. The HTTP POST method allows the client to send data of
unlimited length to the Web server a single time and is useful when posting
information such as credit card numbers.
When overriding this method, leave intact any content headers sent with the
request (including Content-Length, Content-Type, Content-Transfer-Encoding,
Content-Encoding, Content-Base, Content-Language, Content-Location,
Content-MD5, and Content-Range). If your method cannot handle a content
header, it must issue an error message (HTTP 501 - Not Implemented) and
discard the request.
For more information on HTTP 1.1, see RFC 2068
(http://info.internet.isi.edu:80/in-notes/rfc/files/rfc2068.txt).
This method does not need to be either safe or idempotent. Operations that
doPut performs can have side effects for which the user can be held accountable.
When using this method, it may be useful to save a copy of the affected
URL in temporary storage.
If the HTTP PUT request is incorrectly formatted, doPut returns an HTTP
"Bad Request" message.
Called by the server (via the service method) to allow a servlet to handle a
PUT request. The PUT operation allows a client to place a file on the server
and is similar to sending a file by FTP.
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.
GET:
POST:
HEAD:
1.3 For each of the following operations, identify the interface and method name that should be used:
ServletRequest object provides data including
parameter name and values, attributes, and an input stream. Interfaces that extend
ServletRequest can provide additional protocol-specific data (for example, HTTP
data is provided by HttpServletRequest).
The following methods are included in ServletRequest interface.
Returns: an immutable java.util.Map containing parameter names as keys
and parameter values as map values. The keys in the parameter map are of
type String. The values in the parameter map are of type String array.
Returns a java.util.Map of the
parameters of this request.
Request parameters
are extra information sent with the request. For HTTP servlets,
parameters
are contained in the query string or posted form data.
Returns: an Enumeration of String objects, each String containing the
name of a request parameter; or an empty Enumeration if the request has no
parameters
Returns an Enumeration of String objects containing the names of the
parameters contained in this request. If the request has no parameters, the
method returns an empty Enumeration.
Returns an array of String objects containing all of the values the given
request parameter has, or null if the parameter does not exist.
If the parameter has a single value, the array has a length of 1.
You should only use this method when you are sure the parameter has only
one value. If the parameter might have more than one value, use getParameterValues(String).
If you
use this method with a multivalued parameter, the value returned is
equal to the first value in the array returned by getParameterValues.
If the parameter data was sent in the request body, such as occurs with an
HTTP POST request, then reading the body directly via getInputStream()
or getReader() can interfere with the execution of this method.
Returns the value of a request parameter as a String,or null if the parameter
does not exist. Request parameters are extra information sent with the
request. For HTTP servlets, parameters are contained in the query string or
posted form data.
interface ServletConfig --- A servlet configuration object used by a servlet container to pass information to a servlet during initialization.
Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist.
Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty
Enumeration if the servlet has no initialization parameters.
interface HttpServletRequest extends the ServletRequest interface to provide request information for HTTP servlets.
The date is returned as the number of milliseconds since January 1, 1970
GMT. The header name is case insensitive.
If the request did not have a header of the specified name, this method returns
-1. If the header can’t be converted to a date, the method throws an IllegalArgumentException.
Returns the value of the specified request header as a long value that represents
a Date object. Use this method with headers that contain dates, such as
If-Modified-Since.
Returns the value of the specified request header as a String. If the request
did not include a header of the specified name, this method returns null. The
header name is case insensitive. You can use this method with any request
header.
Some servlet containers do not allow servlets to access headers
using this method, in which case this method returns null
Returns: an enumeration of all the header names sent with this request; if
the request has no headers, an empty enumeration; if the servlet container
does not allow servlets to use this method, null
Returns an enumeration of all the header names this request contains. If the
request has no headers, this method returns an empty enumeration.
Some headers, such as Accept-Language can be sent by clients as several
headers each with a different value rather than sending the header as a
comma separated list.
If the request did not include any headers of the specified name, this method
returns an empty Enumeration. The header name is case insensitive. You can
use this method with any request header.
Returns all the values of the specified request header as an Enumeration of
String objects.
The header name is case insensitive.
Returns the value of the specified request header as an int. If the request
does not have a header of the specified name, this method returns -1. If the
header cannot be converted to an integer, this method throws a NumberFormatException.
(which is an unchecked exception).
HttpServletResponse extends ServletResponse
interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies.
The servlet container creates an HttpServletResponse object and passes it as an argument to the servlet's service methods (doGet, doPost, etc).
Sets a response header with the given name and date-value. The date is specified in terms of milliseconds since the epoch. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value.
Sets a response header with the given name and value. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value.
Sets a response header with the given name and integer value. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value.
Adds a response header with the given name and date-value. The date is specified in terms of milliseconds since the epoch. This method allows response headers to have multiple values.
Adds a response header with the given name and value. This method allows response headers to have multiple values.
Adds a response header with the given name and integer value. This method allows response headers to have multiple values.
Sets the locale of the response, setting the headers (including the Content-Type’s charset) as appropriate. This method should be called before a call to getWriter() . By default, the response locale is the default locale for the server.
Sets the content type of the response being sent to the client. The content type may include the type of character encoding used, for example, text/html; charset=ISO-8859-4. If obtaining a PrintWriter, this method should be called first.
Returns a PrintWriter object that can send character text to the client. The character encoding used is the one specified in the charset= property of the setContentType(java.lang.String) method, which must be called before calling this method for the charset to take effect. If necessary, the MIME type of the response is modified to reflect the character encoding used. Calling flush() on the PrintWriter commits the response. Either this method or getOutputStream() may be called to write the body, not both.
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Here we go");
...
|
Throws:
java.io.UnsupportedEncodingException -(checked exception, subclass of IOException)
if the charset specified in setContentType cannot be used
java.lang.IllegalStateException - (runtime exception)
if the getOutputStream method has already been called for this response object
java.io.IOException -
if an input or output exception occurred
Note: here java.lang.IllegalStateException is a runtime exception. But javax.jms.IllegalStateException and javax.resource.spi.IllegalStateException are checked exceptions.
public javax.servlet.ServletOutputStream ServletResponse.getOutputStream() throws java.io.IOException Returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data. Calling flush() on the ServletOutputStream commits the response. Either this method or getWriter() may be called to write the body, not both.
Throws:
java.lang.IllegalStateException - (runtime exception)
if the getWriter method has been called on this response
java.io.IOException - if an input or output exception occurred
For mix binary and text data, for example, to create a multipart response, use a ServletOutputStream and manage the character sections manually.
public void HttpServletResponse.sendRedirect(java.lang.String location) throws java.io.IOException Sends a temporary redirect response to the client using the specified redirect
location URL. This method can accept relative URLs; the servlet container must
convert the relative URL to an absolute URL before sending the response to the
client. If the location is relative without a leading '/' the container interprets
it as relative to the current request URI. If the location is relative with a
leading '/' the container interprets it as relative to the servlet container root.
If the response has already been committed, this method throws an IllegalStateException.
After using this method, the response should be considered to be committed
and should not be written to.
Throws:
java.io.IOException -
If an input or output exception occurs
java.lang.IllegalStateException - (runtime exception)
If the response was committed
Encodes the specified URL for use in the sendRedirect method or, if encoding
is not needed, returns the URL unchanged. The implementation of this method
includes the logic to determine whether the session ID needs to be encoded
in the URL. Because the rules for making this determination can differ from
those used to decide whether to encode a normal link, this method is seperate
from the encodeURL method.
All URLs sent to the HttpServletResponse.sendRedirect method should be run
through this method. Otherwise, URL rewriting cannot be used with browsers
which do not support cookies.
No exception thrown.
Note: encodeRedirectUrl() method is deprecated, which is used before version 2.1
1.4 Identify the interface and method to access values and resources and to set object attributes within the following three Web scopes:
interface:
public interface HttpServletRequest
extends ServletRequest
|
methods in ServletRequest:
Attributes can be set two ways. The servlet container may set attributes to make available custom information about a request. For example, for requests made using HTTPS, the attribute javax.servlet.request.X509Certificate can be used to retrieve information on the certificate of the client. Attributes can also be set programatically using setAttribute(java.lang.String, java.lang.Object). This allows information to be embedded into a request before a RequestDispatcher call.
Attribute names should follow the same conventions as package names. This specification reserves names matching java.*, javax.*, and sun.*.
Returns: an Enumeration of strings containing the names of the request's attributes
Attribute names should follow the same conventions as package names. Names beginning with java.*, javax.*, and com.sun.*, are reserved for use by Sun Microsystems.
If the value passed in is null, the effect is the same as calling removeAttribute(java.lang.String).
Attribute names should follow the same conventions as package names. Names beginning with java.*, javax.*, and com.sun.*, are reserved for use by Sun Microsystems.
Returns: a String containing the name of the chararacter encoding, or null if the request does not specify a character encoding
Returns: an integer containing the length of the request body or -1 if the length is not known
Returns: a String containing the name of the MIME type of the request, or null if the type is not known
Returns: a String containing the protocol name and version number
Returns: a String containing the name of the scheme used to make this request
Returns the host name of the server that received the request. For HTTP servlets, same as the value of the CGI variable SERVER_NAME.
Returns: a String containing the name of the server to which the request was sent
Returns: an integer specifying the port number
Returns: a String containing the IP address of the client that sent the request
Returns: a String containing the fully qualified name of the client
Returns: the preferred Locale for the client
Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the client based on the Accept-Language header. If the client request doesn't provide an Accept-Language header, this method returns an Enumeration containing one Locale, the default locale for the server.
Returns: an Enumeration of preferred Locale objects for the client
methods in the HttpServletRequest
Same as the value of the CGI variable AUTH_TYPE.
Returns: one of the static members BASIC_AUTH, FORM_AUTH, CLIENT_CERT_AUTH, DIGEST_AUTH (suitable for == comparison) indicating the authentication scheme, or null if the request was not authenticated.
Returns: a String specifying the name of the method with which this request was made
Returns: a String, decoded by the web container, specifying extra path information that comes after the servlet path but before the query string in the request URL; or null if the URL does not have any extra path information
If the URL does not have any extra path information, this method returns null. The web container does not decode this string.
Returns: a String specifying the real path, or null if the URL does not have any extra path information
Returns: a String specifying the portion of the request URI that indicates the context of the request
Returns: a String containing the query string or null if the URL contains no query string. The value is not decoded by the container.
Returns: a String specifying the login of the user making this request, or null
Returns: a java.security.Principal containing the name of the user making this request; null if the user has not been authenticated
Returns the session ID specified by the client. This may not be the same as the ID of the actual session in use. For example, if the request specified an old (expired) session ID and the server has started a new session, this method gets a new session with a new ID. If the request did not specify a session ID, this method returns null.
Returns: a String specifying the session ID, or null if the request did not specify a session ID
POST /some/path.html HTTP/1.1 /some/path.html GET http://foo.bar/a.html HTTP/1.0 /a.html HEAD /xyz?a=b HTTP/1.1 /xyzTo reconstruct an URL with a scheme and host, use HttpUtils.getRequestURL(javax.servlet.http.HttpServletRequest).
Returns: a String containing the part of the URL from the protocol name up to the query string
Returns: a StringBuffer object containing the reconstructed URL
Returns: a String containing the name or path of the servlet being called, as specified in the request URL, decoded.
If create is false and the request has no valid HttpSession, this method returns null.
To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown.
Parameters: true - to create a new session for this request if necessary; false to return null if there's no current session
Returns: the HttpSession associated with this request or null if create is false and the request has no valid session
Returns: the HttpSession associated with this request
interface HttpSession
interface ServletContext
4. Scopes
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.
Servlet interface defines methods to initialize a servlet, to service requests,
and to remove a servlet from the server. These are known as life-cycle methods
and are called in the following sequence:
Called by the servlet container to indicate to a servlet that the servlet is being placed into service. The servlet container calls the init method exactly once after instantiating the servlet. The init method must complete successfully before the servlet can receive any requests.
The servlet container cannot place the servlet into service if the init method throws a ServletException or does not return within a time period defined by the Web server
Parameters: config - a ServletConfig object containing the servlet's configuration and initialization parameters
Points
Parameters: req - the ServletRequest object that contains the client's request res - the ServletResponse object that contains the servlet's response
Throws: ServletException - if an exception occurs that interferes with the servlet's normal operation java.io.IOException - if an input or output exception occurs
Points
Points
Servlet Life Cycle in Servlet 2.3
1.6 Use a RequestDispatcher to include or forward to a Web resource.
public interface javax.servlet.RequestDispatcher{
public void forward(ServletRequest request,
ServletResponse response)
throws ServletException,
java.io.IOException
public void include(ServletRequest request,
ServletResponse response)
throws ServletException,
java.io.IOException
}
|
Defines an object that receives requests from the client and sends
them to any resource (such as a servlet, HTML file, or JSP file) on the server.
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.
This interface is intended to wrap servlets, but a servlet container can create
RequestDispatcher objects to wrap any type of resource.
To get a RequestDispatcher:
in the doGet(request, response) method ... String url="/xxxx/xxx.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forword(request, response); ... |
include:
public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException
public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException
Conditional Get
Servlet Life CycleLoading and Instantiation
The servlet container is responsible for loading and instantiating servlets. The loading
and instantiation can occur when the container is started, or delayed until the
container determines the servlet is needed to service a request.
When the servlet engine is started, needed servlet classes must be located by
the servlet container. The servlet container loads the servlet class using normal
Java class loading facilities. The loading may be from a local file system, a remote
file system, or other network services.
After loading the Servlet class, the container instantiates it for use.
Initialization
After the servlet object is instantiated, the container must initialize the servlet before
it can handle requests from clients. Initialization is provided so that a servlet can
read persistent configuration data, initialize costly resources (such as JDBC™ API
based connections), and perform other one-time activities. The container initializes
the servlet instance by calling the init method of the Servlet interface with a
unique (per servlet declaration) object implementing the ServletConfig interface.
This configuration object allows the servlet to access name-value initialization
parameters from the web application’s configuration information. The configuration
object also gives the servlet access to an object (implementing the ServletContext
interface) that describes the servlet’s runtime environment.
During initialization, the servlet instance can throw an UnavailableException or a
ServletException. In this case the servlet must not be placed into active service
and must be released by the servlet container. The destroy method is not called as it
is considered unsuccessful initialization.
A new instance may be instantiated and initialized by the container after a
failed initialization. The exception to this rule is when an UnavailableException
indicates a minimum time of unavailability, and the container must wait for the
period to pass before creating and initializing a new servlet instance.
In the case of an HTTP request, the objects provided by the container are of
types HttpServletRequest and HttpServletResponse.
Note that a servlet instance placed into service by a servlet container may handle
no requests during its lifetime.
End of Service
The servlet container is not required to keep a servlet loaded for any particular
period of time. A servlet instance may be kept active in a servlet container for a
period of milliseconds, for the lifetime of the servlet container (which could be a
number of days, months, or years), or any amount of time in between.
When the servlet container determines that a servlet should be removed from
service, it calls the destroy method of the Servlet interface to allow the servlet to
release any resources it is using and save any persistent state. For example, the
container may do this when it wants to conserve memory resources, or when it
itself is being shut down.
Before the servlet container calls the destroy method, it must allow any
threads that are currently running in the service method of the servlet to complete
execution, or exceed a server defined time limit.
Once the destroy method is called on a servlet instance, the container may
not route other requests to that 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.