You are on page 1of 74

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.
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:
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


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
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.

Return to top

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.

1. GET:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
---for handling GET, conditional GET, and HEAD requests

Called by the server (via the service method) to allow a servlet to handle a GET
request.

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 responses writer or output stream object, and finally, write
the response data. Its 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.

2. POST:
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
---for handling POST request

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, read the request data, write the response headers, get the
responses writer or output stream object, and finally, write the response data. Its 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.

3. PUT:
public void doPut(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
---for handling PUT request
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.

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.

Return to top

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:

Triggers
1. Typing url directly into a browser,
2. Clicking on a hyperlink,
3. Submitting html form with 'method=get' or no method attribute
Benefits or functionality
1. Designed for getting information (e.g. document, chart, results of query)
2. Can include a query string (some servers limit this to about 240 characters) for
sending information to server
3. Requested page can be bookmarked

POST:
Triggers
1. Submitting html form with 'method=post'
Benefits or functionality
1. Designed for posting information (e.g. credit card #, info to be stored in a db)
2. Passes all its data (of unlimited length) to server as part of its http request body
3. Posts cannot be bookmarked or, in some cases, even reloaded
4. Hides sensitive information from server log by including it in the message body
instead of the url query string

HEAD:

Triggers
1. May be used by a browser to check modification time for purposes of catching
Benefits or functionality
1. Sent by a client when it wants to see only the headers of the response, to
determine the document's size, modification time, or general availability.
2. The service() method treats HEAD requests specially. It calls doGet with a
modified response object, which suppresses any output but retains headers.

Return to top

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

1. Retrieve HTML form parameters from the request

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.

1. java.util.Map getParameterMap()
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 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.

2. java.util.Enumeration getParameterNames()

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 Enumeration of String objects, each String containing the name of a


request parameter; or an empty Enumeration if the request has no parameters

3. java.lang.String[] getParameterValues(java.lang.String name)

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.

4. java.lang.String getParameter(java.lang.String name)

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.

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.

2. Retrieve a servlet initialization parameter

interface ServletConfig --- A servlet configuration object used by a servlet container to


pass information to a servlet during initialization.
1. java.lang.String getInitParameter(java.lang.String name)

Returns a String containing the value of the named initialization parameter,


or null if the parameter does not exist.

2. java.util.Enumeration getInitParameterNames()

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.

3. Retrieve HTTP request header information

interface HttpServletRequest extends the ServletRequest interface to provide request


information for HTTP servlets.

1. long getDateHeader(java.lang.String name)

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.

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 cant be converted to a date,
the method throws an IllegalArgumentException.

2. java.lang.String getHeader(java.lang.String name)

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.

3. java.util.Enumeration getHeaderNames()

Returns an enumeration of all the header names this request contains. If the
request has no headers, this method returns an empty enumeration.

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

4. java.util.Enumeration getHeaders(java.lang.String name)

Returns all the values of the specified request header as an Enumeration of


String objects.

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.

5. int getIntHeader(java.lang.String name)

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).

The header name is case insensitive.

4. Set an HTTP response header; set the content type of the response

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).

1. public void setDateHeader(java.lang.String name, long date)

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.

2. public void setHeader(java.lang.String name, java.lang.String 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.

3. public void setIntHeader(java.lang.String name, int 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.

4. public void addDateHeader(java.lang.String name, long date)

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.

5. public void addHeader(java.lang.String name, java.lang.String value)

Adds a response header with the given name and value. This method allows
response headers to have multiple values.

6. public void addIntHeader(java.lang.String name, int value)

Adds a response header with the given name and integer value. This method
allows response headers to have multiple values.

7. public void setLocale(java.util.Locale loc)

Sets the locale of the response, setting the headers (including the Content-Types
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.

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

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.

5. Acquire a text stream for the response

1. public java.io.PrintWriter ServletResponse.getWriter() throws


java.io.IOException
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.

6. Acquire a binary stream for the response

1. 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.

7. Throws:
8. java.lang.IllegalStateException - (runtime exception)
9. if the getWriter method has been called on this response
10. java.io.IOException - if an input or output exception occurred
11.
12. For mix binary and text data, for example, to create a multipart response, use a
ServletOutputStream and manage the character sections manually.
13. Redirect an HTTP request to another URL
1. 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
2. public java.lang.String
HttpServletResponse.encodeRedirectURL(java.lang.String url)

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

3. public static final int HttpServletResponse.SC_TEMPORARY_REDIRECT


Status code (307) indicating that the requested resource resides temporarily under
a different URI.
4. public static final int HttpServletResponse.SC_MOVED_TEMPORARILY
Status code (302) indicating that the resource has temporarily moved to another
location, but that future references should still use the original URI to access the
resource.

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

1. Request

interface:

1. ServletRequest
2. HttpServletRequest

public interface HttpServletRequest


extends ServletRequest

methods in ServletRequest:

3. public java.lang.Object getAttribute(java.lang.String name)


Returns the value of the named attribute as an Object, or null if no attribute of the
given name exists.

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.*.

4. public java.util.Enumeration getAttributeNames()


Returns an Enumeration containing the names of the attributes available to this
request. This method returns an empty Enumeration if the request has no
attributes available to it.

Returns: an Enumeration of strings containing the names of the request's attributes

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


Stores an attribute in this request. Attributes are reset between requests. This
method is most often used in conjunction with RequestDispatcher.
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).

6. public void removeAttribute(java.lang.String name)


Removes an attribute from this request. This method is not generally needed as
attributes only persist as long as the request is being handled.

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.

7. public java.lang.String getCharacterEncoding()


Returns the name of the character encoding used in the body of this request. This
method returns null if the request does not specify a character encoding

Returns: a String containing the name of the chararacter encoding, or null if the
request does not specify a character encoding

8. public void setCharacterEncoding(java.lang.String env) throws


java.io.UnsupportedEncodingException
Overrides the name of the character encoding used in the body of this request.
This method must be called prior to reading request parameters or reading input
using getReader().
9. public int getContentLength()
Returns the length, in bytes, of the request body and made available by the input
stream, or -1 if the length is not known. For HTTP servlets, same as the value of
the CGI variable CONTENT_LENGTH.

Returns: an integer containing the length of the request body or -1 if the length is
not known

10. public java.lang.String getContentType()


Returns the MIME type of the body of the request, or null if the type is not
known. For HTTP servlets, same as the value of the CGI variable
CONTENT_TYPE.

Returns: a String containing the name of the MIME type of the request, or null if
the type is not known

11. public java.lang.String getProtocol()


Returns the name and version of the protocol the request uses in the form
protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets,
the value returned is the same as the value of the CGI variable
SERVER_PROTOCOL.

Returns: a String containing the protocol name and version number

12. public java.lang.String getScheme()


Returns the name of the scheme used to make this request, for example, http,
https, or ftp. Different schemes have different rules for constructing URLs, as
noted in RFC 1738.

Returns: a String containing the name of the scheme used to make this request

13. public java.lang.String getServerName()

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

14. public int getServerPort()


Returns the port number on which this request was received. For HTTP servlets,
same as the value of the CGI variable SERVER_PORT.

Returns: an integer specifying the port number

15. public java.lang.String getRemoteAddr()


Returns the Internet Protocol (IP) address of the client that sent the request. For
HTTP servlets, same as the value of the CGI variable REMOTE_ADDR.

Returns: a String containing the IP address of the client that sent the request

16. public java.lang.String getRemoteHost()


Returns the fully qualified name of the client that sent the request. If the engine
cannot or chooses not to resolve the hostname (to improve performance), this
method returns the dotted-string form of the IP address. For HTTP servlets, same
as the value of the CGI variable REMOTE_HOST.

Returns: a String containing the fully qualified name of the client

17. public java.util.Locale getLocale()


Returns the preferred Locale that the client will accept content in, based on the
Accept-Language header. If the client request doesn't provide an Accept-
Language header, this method returns the default locale for the server.

Returns: the preferred Locale for the client


18. public java.util.Enumeration getLocales()

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

19. public java.lang.String getAuthType()


Returns the name of the authentication scheme used to protect the servlet. All
servlet containers support basic, form and client certificate authentication, and
may additionally support digest authentication. If the servlet is not authenticated
null is returned.

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.

20. public java.lang.String getMethod()


Returns the name of the HTTP method with which this request was made, for
example, GET, POST, or PUT. Same as the value of the CGI variable
REQUEST_METHOD.

Returns: a String specifying the name of the method with which this request was
made

21. public java.lang.String getPathInfo()


Returns any extra path information associated with the URL the client sent when
it made this request. The extra path information follows the servlet path but
precedes the query string. This method returns null if there was no extra path
information. Same as the value of the CGI variable PATH_INFO.

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

22. public java.lang.String getPathTranslated()


Returns any extra path information after the servlet name but before the query
string, and translates it to a real path. Same as the value of the CGI variable
PATH_TRANSLATED.
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

23. public java.lang.String getContextPath()


Returns the portion of the request URI that indicates the context of the request.
The context path always comes first in a request URI. The path starts with a "/"
character but does not end with a "/" character. For servlets in the default (root)
context, this method returns "". The container does not decode this string.

Returns: a String specifying the portion of the request URI that indicates the
context of the request

24. public java.lang.String getQueryString()


Returns the query string that is contained in the request URL after the path. This
method returns null if the URL does not have a query string. Same as the value of
the CGI variable QUERY_STRING.

Returns: a String containing the query string or null if the URL contains no query
string. The value is not decoded by the container.

25. public java.lang.String getRemoteUser()


Returns the login of the user making this request, if the user has been
authenticated, or null if the user has not been authenticated. Whether the user
name is sent with each subsequent request depends on the browser and type of
authentication. Same as the value of the CGI variable REMOTE_USER.

Returns: a String specifying the login of the user making this request, or null

26. public java.security.Principal getUserPrincipal()


Returns a java.security.Principal object containing the name of the current
authenticated user. If the user has not been authenticated, the method returns null.

Returns: a java.security.Principal containing the name of the user making this


request; null if the user has not been authenticated

27. public java.lang.String getRequestedSessionId()

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

28. public java.lang.String getRequestURI()


Returns the part of this request's URL from the protocol name up to the query
string in the first line of the HTTP request. The web container does not decode
this String. For example: First line of HTTP request Returned Value
29. POST /some/path.html HTTP/1.1 /some/path.html
30. GET http://foo.bar/a.html HTTP/1.0 /a.html
31. HEAD /xyz?a=b HTTP/1.1 /xyz

To 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

32. public java.lang.StringBuffer getRequestURL()


Reconstructs the URL the client used to make the request. The returned URL
contains a protocol, server name, port number, and server path, but it does not
include query string parameters. Because this method returns a StringBuffer, not a
string, you can modify the URL easily, for example, to append query parameters.
This method is useful for creating redirect messages and for reporting errors.

Returns: a StringBuffer object containing the reconstructed URL

33. public java.lang.String getServletPath()


Returns the part of this request's URL that calls the servlet. This includes either
the servlet name or a path to the servlet, but does not include any extra path
information or a query string. Same as the value of the CGI variable
SCRIPT_NAME.

Returns: a String containing the name or path of the servlet being called, as
specified in the request URL, decoded.

34. public HttpSession getSession(boolean create)


Returns the current HttpSession associated with this request or, if if there is no
current session and create is true, returns a new session.

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

35. public HttpSession getSession()


Returns the current session associated with this request, or if the request does not
have a session, creates one.

Returns: the HttpSession associated with this request

2. Session

interface HttpSession

1. Enumeration getAttributeNames()
returns empty enumeration if no attributes; IllegalStateException if session
invalidated
2. Object getAttribute(String name)
returns null if no such object
3. void setAttribute(java.lang.String name, java.lang.Object value)
4. void removeAttribute(java.lang.String name)
5. String getId()
returns unique session identifier assigned by servlet container
6. long getLastAccessedTime()
time when client last sent a request associated with this session
7. int getMaxInactiveInterval()
returns number of seconds this session remains open between client requests; -1 if
session should never expire
8. void setMaxInactiveInterval(int interval)
3. Context

interface ServletContext
1. Enumeration getAttributeNames()
Returns an Enumeration containing the attribute names available within this
servlet context.
2. Object getAttribute(String name)
Returns the servlet container attribute with the given name, or null if there is no
attribute by that name.
3. void setAttribute(String name, java.lang.Object object)
Binds an object to a given attribute name in this servlet context.
4. void removeAttribute(String name)
Removes the attribute with the given name from the servlet context.
5. ServletContext getContext(String uripath)
Returns a ServletContext object that corresponds to a specified URL on the server.
6. String getInitParameter(String name)
Returns a String containing the value of the named context-wide initialization
parameter, or null if does not exist.
7. Enumeration getInitParameterNames()
Returns names of the context's initialization parameters as Enumeration of String
objects
8. int getMajorVersion()
Returns the major version of the Java Servlet API that this servlet container
supports.
9. int getMinorVersion()
Returns the minor version of the Servlet API that this servlet container supports.
10. String getMimeType(String file)
Returns the MIME type of the specified file, or null if the MIME type is not
known.
11. RequestDispatcher getNamedDispatcher(String name)
Returns a RequestDispatcher object that acts as a wrapper for the named servlet.
12. RequestDispatcher getRequestDispatcher(String path)
Returns a RequestDispatcher object that acts as a wrapper for the resource located
at the given path.
13. String getRealPath(String path)
Returns a String containing the real path for a given virtual path.
14. java.net.URL getResource(String path)
Returns a URL to the resource that is mapped to a specified path.
15. InputStream getResourceAsStream(String path)
Returns the resource located at the named path as an InputStream object.
16. String getServerInfo()
Returns the name and version of the servlet container on which the servlet is
running.

4. Scopes

Application scope: "global memory", ServletContext object.


Session scope: specific to an individual user seesion, HttpSession object. e.g. shopping
cart
Request scope: specific to an individual server request, ServletRequest object
Page scope: applicable only to a single JSP page, pageContext object

Return to top

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:

The servlet is constructed, then initialized with the init method.


Any calls from clients to the service method are handled.
The servlet is taken out of service, then destroyed with the destroy method, then garbage
collected and finalized.

1. public void init(ServletConfig config) throws ServletException

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
o called after server constructs the servlet instance and before the server handles
any requests
o depending on the server and web app configuration, init() may be called at any of
these times:
1. when server starts,
2. when the servlet is first requested, just before the service() method is
invoked,
3. at the request of the server administrator
o if servlet specifies "load-on-startup/" in its web.xml file, then upon server startup,
the server will create an instance of the servlet and call its init() method.
o typically used to perform servlet initialization, e.g. loading objects used by servlet
to handle requests, reading in servlet init parameters, starting a background
thread.
o servlet cannot be placed into service if init method throws ServletException or
does not return within a server-defined time period
o init() can only be called once per servlet instance

2. public void service(ServletRequest req, ServletResponse res) throws


ServletException, java.io.IOException

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

o Called by the servlet container to allow the servlet to respond to a request.


o Only called after the servlet's init() method has completed successfully.

o The status code of the response always should be set for a servlet that throws or
sends an error.
o Servlets typically run inside multithreaded servlet containers that can handle
multiple requests concurrently.
o Developers must be aware to synchronize access to any shared resources such as
files, network connections, and as well as the servlet's class and instance
variables.
3. public void destroy()
Points

o Called by the servlet container to indicate to a servlet that the servlet is being
taken out of service.
o Only called once all threads within the servlet's service method have exited or
after a timeout period has passed.
o After the servlet container calls this method, it will not call the service method
again on this servlet.
o gives the servlet an opportunity to clean up any resources that are being held (for
example, memory, file handles, threads) and make sure that any persistent state is
synchronized with the servlet's current state in memory.
o destroy()called once per servlet instance; destroy() not called if server crashes, so
should save state (if needed) periodically after servicing requests

End of Service issue specified in Servlet 2.3

4. NOTES: Servlet reloading


o Most servers automatically reload a servlet after its class file (under servlet dir,
e.g. WEB-INF/classes) changes. when a server dispatches a request to a servlet, it
first checks whether the servlet's class file has changed on disk. If it has, then the
server creates a new custom class loader, and reloads the entire web application
context.
o class reloading is not based on support class changes or on changes in classes
found in the server's classpath, which are loaded by the core, primordial class
loader.

Servlet Life Cycle in Servlet 2.3

Return to top

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);
...

1. include:

public void include(ServletRequest request, ServletResponse response) throws


ServletException, IOException

o Includes the content of a resource (servlet, JSP page, HTML file) in the response.
In essence, this method enables programmatic server-side includes.
o The ServletRequest object has its path elements (e.g. attributes request_uri,
context_path, and servlet_path) and parameters remain unchanged from the
caller's.
o The included servlet cannot change the response status code or set headers; any
attempt to make a change is ignored.
o The request and response parameters must be the same objects as were passed to
the calling servlet's service method.
o The included resource must use the same output mechanism (e.g. PrintWriter or
ServletOutputStream) as the caller's
o Information can be passed to target using attached query string or using request
attributes set with setAttribute() method.
2. forward:

public void forward(ServletRequest request, ServletResponse response) throws


ServletException, IOException

o Forwards a request from a servlet to another resource (servlet, JSP file, or HTML
file) on the server. This method allows one servlet to do preliminary processing of
a request and another resource to generate the response. The forwarding servlet
generates no output, but may set headers.
o The ServletRequest object has its path attributes adjusted to match the path of the
target resource. Any new request parameters are added to the original.
o forward() should be called before the response has been committed to the client
(before response body output has been flushed). If the response already has been
committed, this method throws an IllegalStateException. Uncommitted output in
the response buffer is automatically cleared before the forward.
o The request and response parameters must be the same objects as were passed to
the calling servlet's service method.
o Information can be passed to target using attached query string or using request
attributes set with setAttribute() method.
o forwarding to an html page containing relative url's included (e.g. "IMG" tags) is
a bad idea, because forward() does not notify client about the directory from
which the page is served, hence the links may be broken. Instead, use
sendRedirect().
3. Note: to get a request dispatcher object:
o public RequestDispatcher ServletRequest.getRequestDispatcher(String path)
- path may be relative, and cannot extend outside current servlet context
o public RequestDispatcher ServletContext.getNamedDispatcher(String name)
- name is the registered servlet name in web.xml file
o public RequestDispatcher ServletContext.getRequestDispatcher(String path)
- accepts only absolute paths, and not relative paths

Conditional Get
The HttpServlet interface defines the getLastModified method to support conditional GET
operations. A conditional GET operation requests a resource be sent only if it has been modified
since a specified time. In appropriate situations, implementation of this method may aid efficient
utilization of network resources.

Return to top

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 implement directly, or indirectly through the GenericServlet or
HttpServlet abstract classes.
Loading 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 applications configuration information. The configuration
object also gives the servlet access to an object (implementing the ServletContext interface) that
describes the servlets 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.

Return to top

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 servlets class. After the destroy method completes, the servlet
container must release the servlet instance so that it is eligible for garbage collection.

Return to top

SECTION 2: THE STRUCTURE AND


DEPLOYMENT OF MODERN SERVLET
WEB APPLICATIONS
Section 2

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:
The WebApp deployment descriptor
The WebApp class files

Any auxiliary JAR files


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

Servlet class
Initialization parameters

URL to named servlet mapping

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:

1. The WebApp deployment descriptor


2. The WebApp class files
3. Any auxiliary JAR files

1. the structure of a Web Application

The following web application hierarchy is placed under a context root directory within
the server's WebApps directory (or something similar, depending on the server) :

o /[any files to be served to the client, e.g. index.html, images/banner.gif]


o /WEB-INF/web.xml

o /WEB-INF/lib/[any required jar files]

o /WEB-INF/classes/[servlet and support class files in their package hierarchies,


e.g. com/mycorp/frontend/CorpServlet.class]
2. the structure of a Web Archive file
o this is a JAR archive of the Web Application structure above; it just has a WAR
extension so that people and tools know to treat it differently
o a WAR file can be placed in a server's WebApps directory, and the server will
extract it on start up
3. the name of a WebApp deployment descriptor: web.xml
4. the name of the directories where you place the following

1. The WebApp deployment descriptor at /WEB-INF/web.xml

2. The WebApp class files at /WEB-INF/classes/

3. Any auxiliary JAR files at /WEB-INF/lib/


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

1. Servlet instance
<servlet> {servlet-name, servlet-class, init-param, etc.} </servlet>
declares a servlet instance; included within <web-app> </web-app> tags
2. Servlet name
<servlet-name></servlet-name>
registers the servlet under a specific name
3. Servlet class
<servlet-class></servlet-class>
contains the fully qualified class name of the servlet
4. Initialization parameters
<init-param> {param-name, param-value} </init-param>
defines values that can be set at deployment time and read at run-time via
ServletConfig.getInitParameter(String name)
5. URL to named servlet mapping
6. <servlet-mapping>
7. <servlet-name> helloServlet</servlet-name>
8. <url-pattern> /hello.html </url-pattern>
9. </servlet-mapping>

this maps http://server:port/context_root/hello.html to the helloServlet servlet.


zero or more mappings may be defined per web app
4 types of mappings, searched in the following order:

(a) explicit mappings, e.g. /hello.html


(b) path prefix mappings e.g. /dbfile/*
(c) extension mappings e.g. *.jsp or *.gif
(d) the default mapping "/", identifying the default servlet for the web
app

Return to top

SECTION 3: THE SERVLET CONTAINER


MODEL
Section 3

3.1 Identify the uses for and the interfaces (or classes) and methods to achieve the following
features:
Servlet context init. parameters
Servlet context listener

Servlet context attribute listener

Session attribute listeners


3.2 Identify the WebApp deployment descriptor element name that declares the following
features:
Servlet context init. parameters
Servlet context listener

Servlet context attribute listener

Session attribute listeners


3.3 Distinguish the behavior of the following in a distributable:
Servlet context init. parameters
Servlet context listener

Servlet context attribute listener

Session attribute listeners

Section 3 - The Servlet Container Model


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

1. Servlet context init. parameters

The ServletContext interface defines a servlets view of the web application within
which the servlet is running. The Container Provider is responsible for providing an
implementation of the ServletContext interface in the servlet container. Using the
ServletContext object, a servlet can log events, obtain URL references to resources, and
set and store attributes that other servlets in the context can access.

o purpose: defines init parameters accessible by all servlets in the web


application context; settable at deployment-time, but accessible at run-time
o interfaces (or classes): javax.servlet.ServletContext

o methods:
public Enumeration getInitParameterNames()
public String getInitParameter(String name)
o webapp deployment descriptor element name:
<context-param> {param-name, param-value} </context-param>
o behavior in a distributable: Consider that a different instance of the
ServletContext may exist on each different JVM and/or machine. Therefore, the
context should not be used to store application state. Any state should be stored
externally, e.g. in a database or EJB.
2. Servlet context listener

o purpose: An object that implements the ServletContextListener interface is


notified when its web app context is created or destroyed
o interfaces (or classes): javax.servlet.ServletContextListener

o methods:
void contextInitialized(ServletContextEvent e):
called during web server startup or when context is added or reloaded; requests
will not be handled until this method returns
void contextDestroyed(ServletContextEvent e):
called during web server shutdown or when context is removed or reloaded;
request handling will be stopped before this method is called
o webapp deployment descriptor element name:
o <listener>
o <listener-class> {fully qualified class name} </listener-
class>
o </listener>

o behavior in a distributable:
Each context instance (on different jvm's and/or machines) will have its own
instance of the listener object. Therefore, if a context on one jvm/machine is
initialized or destroyed, it will not trigger a listener on any other jvm/machine.
3. Servlet context attribute listener

o purpose: An object that implements the ServletContextAttributeListener


interface is notified when attributes are added to or removed from its web app
context
o interfaces (or classes): javax.servlet.ServletContextAttributeListener

o methods:
void
attributeAdded/attributeRemoved/attributeReplaced(ServletContextAttribut
eEvent e)
o webapp deployment descriptor element name:
o <listener>
o <listener-class> {fully qualified class name} </listener-
class>
o </listener>

o behavior in a distributable:
Addition, removal or replacement of an attribute in a context will only affect the
listener for that context, and not other context "instances" on other jvm's and/or
machines.
4. Session attribute listeners (HttpSession, Session Activation)

o purpose: An object that implements the HttpSessionAttributeListener


interface is notified when a session attribute is added, removed or replaced
o interfaces (or classes): javax.servlet.http.HttpSessionAttributeListener

o methods:
void
attributeAdded/attributeRemoved/attributeReplaced(HttpSessionBindingEv
ent e)
o webapp deployment descriptor element name:
o <listener>
o <listener-class> {fully qualified class name} </listener-
class>
o </listener>

o behavior in a distributable: sessions may migrate from one jvm or machine to


another; hence the session unbind event may occur on a different jvm/machine
than the session bind event.
5. Http Session listeners

o purpose: An object that implements the HttpSessionListener interface is


notified when a session is created or destroyed in its web app context
o interfaces (or classes): javax.servlet.http.HttpSessionListener

o methods:
void sessionCreated(HttpSessionEvent e)
void sessionDestroyed(HttpSessionEvent e)
- called when session is destroyed (invalidated)
o webapp deployment descriptor element name:
o <listener>
o <listener-class> {fully qualified class name} </listener-
class>
o </listener>

o behavior in a distributable: sessions may migrate from one jvm or machine to


another; hence the session destroy event may occur on a different jvm/machine
than the session create event.
6. Http Session Activation listeners

o purpose: Designed to handle sessions that migrate from one server to


another. The listener is notified when any session is about to passivate(move) and
when the session is about to activate(become alive) on the second host. It gives an
app the chance to, for example, persist nonserializable data across jvm's
o methods:
void sessionWillPassivate(HttpSessionEvent e)
session is about to move; it will already be out of service when this method is
called
void sessionDidActivate(HttpSessionEvent e)
session has been activated on new server; session will not yet be in service when
this method is called
o webapp deployment descriptor element name:
o <listener>
o <listener-class> {fully qualified class name} </listener-
class>
o </listener>

3.2 Identify the WebApp deployment descriptor element name that declares the following
features:

1. Servlet context init. parameters


2. <context-param> {param-name, param-value} </context-param>

3. Servlet context listener


4. <listener>
5. <listener-class> {fully qualified class name} </listener-class>
6. </listener>

7. Servlet context attribute listener


8. <listener>
9. <listener-class> {fully qualified class name} </listener-class>
10. </listener>

11. Session attribute listeners


12. <listener>
13. <listener-class> {fully qualified class name} </listener-class>
14. </listener>
3.3 Distinguish the behavior of the following in a distributable:

1. Servlet context init. parameters

behavior in a distributable: Consider that a different instance of the ServletContext


may exist on each different JVM and/or machine. Therefore, the context should not be
used to store application state. Any state should be stored externally, e.g. in a database or
ejb.

2. Servlet context listener

behavior in a distributable: Each context instance (on different jvm's and/or


machines) will have its own instance of the listener object. Therefore, if a context on one
jvm/machine is initialized or destroyed, it will not trigger a listener on any other
jvm/machine.

3. Servlet context attribute listener

behavior in a distributable: Addition, removal or replacement of an attribute in a


context will only affect the listener for that context, and not other context "instances" on
other jvm's and/or machines

4. Session attribute listeners

behavior in a distributable: sessions may migrate from one jvm or machine to


another; hence the session unbind event may occur on a different jvm/machine than the
session bind event.

Return to top

SECTION 4: DESIGNING AND


DEVELOPING SERVLETS TO HANDLE
SERVER-SIDE EXCEPTIONS
Section 4

4.1 For each of the following cases, identify correctly constructed code for handling business
logic exceptions, and match that code with correct statements about the code's behavior: Return an
HTTP error using the sendError response method; Return an HTTP error using the setStatus
method.
4.2 Given a set of business logic exceptions, identify the following: The configuration that the
deployment descriptor uses to handle each exception; How to use a RequestDispatcher to forward
the request to an error page; Specify the handling declaratively in the deployment descriptor.
4.3 Identify the method used for the following: Write a message to the WebApp log; Write a
message and an exception to the WebApp log.

Section 4 - Designing and Developing Servlets


to Handle Server-side Exceptions
4.1 For each of the following cases, identify correctly constructed code for handling business
logic exceptions, and match that code with correct statements about the code's behavior: Return
an HTTP error using the sendError response method; Return an HTTP error using the setStatus
method.

return an http error using sendError

public void HttpServletResponse.sendError (int statusCode[, String statusMessage])


throws IllegalStateException, IOException
the sendError() method causes the server to generate and send an appropriate server-
specific page describing the error (unless <error-page> defined in web.xml)
with the two-argument version of this method, the server may include the status message
in the error page, depending on the server implementation
must be called before response body is committed, else throws IllegalStateException

return an http error using setStatus

public void HttpServletResponse.setStatus(int statusCode)


if this is not called, the server by default sets the status code to SC_OK(200).
example status codes:
HttpServletResponse.SC_OK(200),
SC_NOT_FOUND(404),
SC_NO_CONTENT(204),
SC_MOVED_TEMPORARILY/PERMANENTLY(302/301),
SC_UNAUTHORIZED(401),
SC_INTERNAL_SERVER_ERROR(500),
SC_NOT_IMPLEMENTED(501),
SC_SERVICE_UNAVAILABLE(503)

calling setStatus() on an error leaves a servlet with the responsibility of generating the
error page
must be called before the response is committed, otherwise call is ignored

4.2 Given a set of business logic exceptions, identify the following: The configuration that the
deployment descriptor uses to handle each exception; How to use a RequestDispatcher to
forward the request to an error page; Specify the handling declaratively in the deployment
descriptor.

configuring deployment descriptor for error handling

<web-app>
<error-page>
<error-code> 404 </error-code>
<location> /404.html </location>
</error-page>
</web-app>

this specifies that any call to sendError(), from within this web app, with 404 error code
should display /404.html; this includes requests for static pages that result in 404 error
code
the value of location must begin with '/', treated as base in the context root, and must refer
to a resource within the context.
<location> may be dynamic (e.g. jsp, servlet); for these, the server makes available the
following request attributes: javax.servlet.error.status_code and
javax.servlet.error.message

configuring deployment descriptor for exception handling

<web-app>
<error-page>
<exception-type> javax.servlet.ServletException</exception-type>
<location> /servlet/ErrorDisplay </location>
</error-page>
</web-app>

how the server handles exceptions thrown by a servlet is server-dependent, unless an
<error-page> entry exists for a specific exception type or a superclass
<location> may be dynamic (e.g. jsp, servlet); for these, the server makes available the
following request attributes: javax.servlet.error.exception_type &
javax.servlet.error.message; the exception object itself is not made available; hence no
way to get a stack trace
servlets must catch all exceptions except those that subclass ServletException,
IOException and RuntimeException (IOException may be caused by client closing the
socket by exiting the browser)
a ServletException may be created with a message and a "root cause", both optional, e.g.
{ throw new ServletException("execution interrupted", InterruptedException); }
public Throwable ServletException.getRootCause() returns the root cause exception
javax.servlet package also defines a subclass of ServletException called
UnavailableException(String msg[, int seconds]), which causes server to take servlet out
of service

using RequestDispatcher to forward to an error page: see section 1.6 above for details

forward:

public void forward(ServletRequest request, ServletResponse response) throws


ServletException, IOException
Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on
the server. This method allows one servlet to do preliminary processing of a request and
another resource to generate the response. The forwarding servlet generates no output,
but may set headers.
The ServletRequest object has its path attributes adjusted to match the path of the target
resource. Any new request parameters are added to the original.
forward() should be called before the response has been committed to the client (before
response body output has been flushed). If the response already has been committed, this
method throws an IllegalStateException. Uncommitted output in the response buffer is
automatically cleared before the forward.
The request and response parameters must be the same objects as were passed to the
calling servlet's service method.
Information can be passed to target using attached query string or using request attributes
set with setAttribute() method.
forwarding to an html page containing relative url's included (e.g. "IMG" tags) is a bad
idea, because forward() does not notify client about the directory from which the page is
served, hence the links may be broken. Instead, use sendRedirect().

Note: to get a request dispatcher object:


public RequestDispatcher ServletRequest.getRequestDispatcher(String path) - path
may be relative, and cannot extend outside current servlet context
public RequestDispatcher ServletContext.getNamedDispatcher(String name) - name
is the registered servlet name in web.xml file
public RequestDispatcher ServletContext.getRequestDispatcher(String path) -
accepts only absolute paths, and not relative paths

4.3 Identify the method used for the following: Write a message to the WebApp log; Write a
message and an exception to the WebApp log.

writing a message to the Web App log:

void log(String msg) - Writes the specified message to a servlet log file, usually an event
log.
void log(String message, java.lang.Throwable throwable) - Writes an explanatory
message and a stack trace for a given Throwable exception to the servlet log file.
these methods are available in GenericServlet and ServletContext.

writing a message and an exception to the Web App log:

public void GenericServlet.log(String msg, Throwable t)


writes the given message and the Throwable's stack trace to a servlet log; exact output
format and location of log are server specific

Return to top

SECTION 5: DESIGNING AND


DEVElOPING SERVLETS USING
SESSION MANAGEMENT
Section 5

5.1 Identify the interface and method for each of the following:
Retrieve a session object across multiple requests to the same or different servlets within
the same WebApp
Store objects into a session object
Retrieve objects from a session object
Respond to the event when a particular object is added to a session
Respond to the event when a session is created and destroyed

Expunge a session object


5.2 Given a scenario, state whether a session object will be invalidated.
5.3 Given that URL-rewriting must be used for session management, identify the design
requirement on session-related HTML pages.

Section 5 - Designing and Developing Servlets


Using Session Management
5.1 Identify the interface and method for each of the following:

1. Retrieve a session object across multiple requests to the same or different servlets within
the same WebApp

o public HttpSession HttpServletRequest.getSession([boolean create])

o if no argument provided, then server will automatically create a new session


object if none exists for the user in the web app context
o to make sure the session is properly maintained, getSession must be called at least
once before committing the response
o sessions are scoped at the web application level; so a servlet running inside one
context cannot access session information saved by another context.
o behind the scenes, the client's session id is usually saved on the client in a cookie
called JSESSIONID. For client that don't support cookies, the session ID can be
sent as part of a rewritten URL, encoded using a jsessionid path parameter.
o note that a requested session id may not match the id of the session returned by
the getSession() method, such as when the id is invalid. one can call
req.isRequestedSessionIDValid() to test if the requested session id (that which
was defined in the rewritten url or the persistent cookie) is valid.
2. Store objects into a session object

o public void HttpSession.setAttribute(String name, Object value)


throws IllegalStateException
o binds the specified object under the specified name. Any existing binding with the
same name is replaced.
o IllegalStateException thrown if session being accessed is invalid

3. Retrieve objects from a session object

o public Object HttpSession.getAttribute(String name) throws


IllegalStateException
-- returns the object bound under the specified name or null if there is no binding
o public Enumeration HttpSession.getAttributeNames() throws
IllegalStateException
-- returns all bound attribute names as an enumeration of Strings (empty enum if
no bindings)
o public void HttpSession.removeAttribute(String name) throws
IllegalStateException
-- removes binding or does nothing if binding does not exist
4. Respond to the event when a particular object is added to a session

o any object that implements the


javax.servlet.http.HttpSessionBindingListener interface is notified when it is
bound to or unbound from a session.
o public void valueBound(HttpSessionBindingEvent event) is called when the
object is bound to a session
o public void valueUnbound(HttpSessionBindingEvent event) is called when the
object is unbound from a session, by being removed or replaced, or by having the
session invalidated
5. Respond to the event when a session is created and destroyed

o An object that implements the HttpSessionListener interface is notified


when a session is created or destroyed in its web app context
o interfaces (or classes): javax.servlet.http.HttpSessionListener

o methods:
void sessionCreated(HttpSessionEvent e)
void sessionDestroyed(HttpSessionEvent e)
- called when session is destroyed (invalidated)
o behavior in a distributable: sessions may migrate from one jvm or machine to
another; hence the session destroy event may occur on a different jvm/machine
than the session create event.
6. Expunge a session object

o public void HttpSession.invalidate()


- causes the session to be immediately invalidated. All objects stored in the
session are unbound. Call this method to implement a "logout".

5.2 Given a scenario, state whether a session object will be invalidated.

1. ideally, a session would be invalidated as soon as the user closed his browser,
browsed to a different site, or stepped away from his desk. Unfortunately, there's no way
for a server to detect any of these events.
2. session may expire automatically, after a set timeout of inactivity (tomcat default is 30
minutes)
3. timeout can be overridden in web.xml file by specifying
4. <web-app>
5. <session-config>
6. <session-timeout> 60</session-timeout>
7. </session-config>
8. </web-app>

9. timeout can be overridden for a specific session by calling


HttpSession.setMaxInactiveInterval(int secs) - negative value indicates session should
never time out.
10. session may expire manually, when it is explicitly invalidated by a servlet by calling
invalidate()
11. a server shutdown may or may not invalidate a session, depending on the capabilities of
the server
12. when a session expires (or is invalidated), the HttpSession object and the data values it
contains are removed from the system; if you need to retain information beyond a session
lifespan, you should keep it in an external location (e.g. a database)

5.3 Given that URL-rewriting must be used for session management, identify the design
requirement on session-related HTML pages.

For a servlet to support session tracking via URL rewriting, it has to rewrite every
local URL before sending it to the client.
public String HttpServletResponse.encodeURL(String url)
public String HttpServletResponse.encodeRedirectURL(String url)
both methods encode the given url to include the session id and returns the new url, or, if
encoding is not needed or is not supported, it leaves the url unchanged. The rules for
when and how to encode are server-specific.
note that when using session tracking based on url rewriting that multiple browser
windows can belong to different sessions or the same session, depending on how the
windows were created and whether the link creating the windows was url rewritten.

Note: Using Cookies:

To send a cookie to a client:


{Cookie cookie = new Cookie("name", "value");
res.addCookie(cookie);}.
To retrieve cookies:
{Cookie[] cookies = req.getCookies();}

Note: Http Session Activation Listener

purpose: Objects that are bound to a session may listen to container events notifying them
when that session will be passivated and when that session has been activated. A
container that migrates sessions between VMs or persists sessions is required to notify all
attributes bound to sessions implementing HttpSessionActivationListener.
void sessionWillPassivate(HttpSessionEvent e)
- session is about to move; it will already be out of service when this method is called
void sessionDidActivate(HttpSessionEvent e)
- session has been activated on new server; session will not yet be in service when this
method is called

Return to top

SECTION 6: DESIGNING AND


DEVELOPING SECURE WEB
APPLICATIONS
Section 6
6.1 Identify correct descriptions or statements about the security issues:
Authentication, authorization
Data integrity

Auditing
Malicious code

Web site attacks


6.2 Identify the deployment descriptor element names, and their structure, that declare the
following:
A security constraint
A Web resource
The login configuration

A security role
6.3 Given an authentication type:
BASIC,
DIGEST,

FORM, and
CLIENT-CERT,

identify the correct definition of its mechanism.

Section 6 - Designing and Developing Secure


Web Applications
6.1 Identify correct descriptions or statements about the security issues:

1. Authentication, authorization

o Authentication: The act of determining the identity of the requesting entity


is known as authentication.
HTTP basic authentication
The Web server authenticates a principal(an entity that can be
authenticated) using the user name and password obtained from the Web
Client.
form-based authentication
The Web container provides an application-specific form for logging in.
(using cookies to authenticate users and allows the app to do its own
credential verification.)
HTTP digest authentication
A Web client authenticates to a Web server by sending the server a
message digest along with its HTTP request message The digest is
computed by employing a one-way hash algorithm to a concatenation of
the HTTP request message and client's password.
Certificate authentication
The client uses a public key certificate to establish its identity and
maintains its own security context.
HTTPS mutual authentication
The proof is bidirectional. The client and server use X.509 certificates to
establish their identity.
Hybrid authentication
Combining several available authentications.
Lazy authentication:
Caller authentication performed on the first access to a protected resource.
Authentication Configuration:
<web-app>
<login-config>
<auth-method> BASIC </auth-method>
<realm-name> jpets </realm-name>
</login-config>
</web-app>

-------------
<web-app>
<login-config>
<auth-method> FORM </auth-method>
<form-login-config>
<form-login-page> login.jsp </form-
login-page>
<form-error-page> error.jsp </form-
error-page>
</form-login-config>
</login-config>
</web-app>
-------------
<web-app>
<login-config>
<auth-method> CLIENT_CERT </auth-method>
</login-config>
</web-app>
o Authorization: After a user presents credentials, such as name/password pair in
order to be authenticated, the process of determining whether that identity can
access a given resource is known as authorization.
Based on the concept of security roles. A security role is a logical grouping
of users defined by an application component provider or application
assembler.
1. declarative security:
using method-permission element in the deployment descriptor
2. programmatic security:
using EJBContext.isCallerInRole or
HttpServletRequest.isRemoteUserInRole methods.
Limiting access to resources to a select set of users or programs
2. Data integrity

o The existing data:


1. relational
2. object-based
3. hierarchical
4. legacy representation
o Face three types of attacks in a distrubuted computing system:
1. be intercepted and modified
2. be captured and reused
3. be monitored by an eavesdropper
o Being able to verify that the content of the communication is not changed during
transmission
o done in the transport-guarantee subelement of the user-data-constraint subelement
of a security-constraint.
o ensured by attaching a message signature to a message.

3. Auditing

o The practice of capturing a record of security-related events to hold users or


systems accountable for their actions.
o Keeping a record of resource access that was granted or denied might be useful
for audit purposes later. To that end, auditing and logs serve the useful purposes of
preventing a break-in or analyzing a break-in postmortem.
4. Malicious code
5. Web site attacks

Face three types of attacks in a distrubuted computing system:

1. be intercepted and modified

2. be captured and reused

3. be monitored by an eavesdropper

Confidentiality:
Ensuring that only the parties involved can understand the communication.

6.2 Identify the deployment descriptor element names, and their structure, that declare the
following:

1. A security constraint

lets you designate URLs that should be protected. It goes hand-in-hand with the
login-config element. It should come immediately before login-config in web.xml and
contains four possible sub-elements.
1. display-name -- an optional element giving a name for IDEs to use
2. web-resource-collection -- a required element that specifies the URLs that should
be protected. Multiple web-resourse-collection entries are permitted within
security-constraint.
3. auth-constraint -- an optional element that designates the abstract roles that should
have access to the URLs.
4. user-data-constraint -- an optional element that specifies whether SSL is required.
2. <web-app>
3. <servlet>
4. <servlet-name>secretSalary</servlet-name>
5. <servlet-class>SalaryServer</servlet-class>
6. </sevlet>
7. <security-constraint>
8. <web-resource-collection>
9. <web-resource-name>protectedResource</web-resource-name>
10. <url-pattern>/servlet/SalaryServer</url-pattern>
11. <url-pattern>/servlet/secretSalary</url-pattern>
12. <http-method>GET</http-method>
13. <http-method>POST</http-method>
14. </web-resource-collection>
15. <auth-constraint>
16. <role-name>manager</role-name>
17. <role-name>ceo</role-name>
18. </auth-constraint> NOTE: if no role-name, then not viewable by any
user; if role-name = "*" then viewable by all roles
19. <user-data-constraint>
20. <transport-guarantee>CONFIDENTIAL</transport-guarantee>
21. </user-data-constraint>
22. </security-constraint>
23. A Web resource

Each security-constraint element must contain one or more web-resource-collection


entries.
The web-resource-name element that gives an arbitrary identifying name, a url-pattern
element that identifies the URLs that should be protected, an optional http-method
element that designates the HTTP commands to which the protection applies(GET, POST,
etc. the default is all methods), and an optional description element providing
documentation.
24. <security-constraint>
25. <web-resource-collection>
26. <web-resource-name>Proprietary</web-resource-name>
27. <url-pattern>/proprietary/*</url-pattern>
28. </web-resource-collection>
29. <web-resource-collection>
30. <web-resource-name>Account</web-resource-name>
31. <url-pattern>/admin/account.jsp</url-pattern>
32. </web-resource-collection>
33. <!-- ... -- >
34. </security-constraint>
35. The login configuration

Use the login-config element to control the authentication method. To use form-
based authentication, supply a value of FORM for the auth-method sub-element and use
the form-login-config subelement to give the locations of the login. and login-failure
pages.
36. <login-config>
37. <auth-method> FORM </auth-method>
38. <form-login-config>
39. <form-login-page>/login.jsp</form-login-page>
40. <form-error-page>/login-error.html</form-error-page>
41. </form-login-config>
42. </login-config>
All the login page requires is a form with an ACTION of j_security_check, a textfield
named j_username, and a password field named j_password. All forms that have
password fields should use a METHOD of POST. For example:

<BODY>
...
<FORM ACTION="j_security_check" METHOD="POST">
<TABLE>
<TR><TD>User Name: <INPUT TYPE="TEXT" NAME="j_username">
<TR><TD>Password: <INPUT TYPE="PASSWORD" NAME="j_password">
<TR><TH><INPUT TYPE="SUBMIT" VALUE="Log In">
</TABLE>
</FORM>
...
</BODY>
43. A security role

The security-role element gives a list of security roles that will appear in the role-
name subelements of the security-role-ref element inside the servlet element.
44. <servlet>
45. <!-- ... -- >
46. <security-role-ref>
47. <role-name>boss</role-name> <!-- New alias -- >
48. <role-link>manager</role-link > <!-- Real name -- >
49. </security-role-ref >
50. </servlet >
51.

Another example:

<web-app>
<!-- ... !-->
<login-config>
<auth-method>BASIC/DIGEST/FORM/CLIENT-CERT</auth-method>
<realm-name>Default </realm-name> <!-- optional, only useful for
BASIC authentication -->
<form-login-config> <!-- optional, only useful for FORM based
authentication -->
<form-login-page>/loginpage.html</form-login-page>
<form-error-page>/errorpage.html</form-error-page>
</form-login-config>
</login-config>
<security-role>
<role-name>manager</role-name>
</security-role> not req'd; explicitly declaring the webapp's roles
supports tool-based manipulation of the file
</web-app>

6.3 Given an authentication type: BASIC, DIGEST, FORM, and CLIENT-CERT, identify the
correct definition of its mechanism.
BASIC

specifies that standard HTTP authentication should be used.


web server maintains a db of usernames and passwords, and identifies certain web
resources as protected. When these are accessed, web server requests username and
password; this information is sent back to the server, which checks it against its database;
and either allows or denies access.
Advantage: very easy to set up; useful for low-security environments, e.g. subscription-
based online newspaper
Disadvantage: provides no confidentiality, no integrity, and only the most basic
authentication. Transmitted passwords are encoded using easily reversable Base64
encoding, unless additional SSL encryption employed. plus, passwords are often stored
on server in clear text

DIGEST

indicates that the client should transmit the username and password using the encrypted
Digest Authentication form.
produced by taking a hash of username, password, uri, http method, and a randomly
generated nonce value provided by server. Server computes digest as well, and compares
with user submitted digest.
Advantage: transactions are somewhat more secure than with basic authentication, since
each digest is valid for only a single uri request and nonce value.
Disadvantage: server must still maintain a database of the original passwords. Digest
authentication is not supported by many browsers

FORM

specifies that the server should check for a reserved session cookie and should redirect
users who do not have it to a designated login page.
the login page must include a form with a POST to the URL "j_security_check" with a
username sent as j_username and a password j_password.
any time the server receives a request for a protected resource, the server checks if the
user has already logged in, e.g. server might look for Principal object in HttpSession
object. If Principal found, then roles are checked against security contraints; if Principal
not authorized, then client redirected to
Advantage: allows users to enter your site through a well-designed, descriptive and
friendly login page
Disadvantage: similar to BASIC, password is transmitted in clear text, unless SSL used
No standard logout mechanism (calling session.invalidate() may work for FORM, but no
guarantees), would need to close browser Error page does not have access to any special
information reporting why access was denied or even which page it should point the user
at to try again Relies on server to authenticate, so only captures username and password,
not custom fields e.g. PIN #.

CLIENT-CERT

the server must use HTTPS(HTTP over SSL) and authenticate users by means of their
Public Key Certificate.
upon accessing a protected resource, the server requests the client's certificate; the client
then sends its signed certificate (many browsers require the client user enter a password
before they will send the certificate), and the server verifies the certificate. If browser has
no certificate, or if it is not authorized, then access is denied.
Advantage: the client will never see a login page, although the browser may prompt for a
password to unlock their certificate before it is sent
Disadvantages: users must obtain and install signed certificates, servers must maintain a
database of all accepted public keys, and servers must support SSL 3.0 in the first place.

Return to top

SECTION 7: DESIGNING AND


DEVELOPING THREAD-SAFE
SERVLETS
Section 7

7.1 Identify which attribute scopes are thread-safe:


Local variables
Instance variables

Class variables
Request attributes
Session attributes

Context attributes
7.2 Identify correct statements about differences between the multi-threaded and single-threaded
servlet models.
7.3 Identify the interface used to declare that a servlet must use the single thread model.

Section 7 - Designing and Developing


Thread-safe Servlets
7.1 Identify which attribute scopes are thread-safe:

1. Local variables Yes, thread-safe


2. Instance variables Not thread-safe
Since a single servlet instance may be handling multiple service requests at any given
time.
3. Class variables Not thread-safe
Since multiple servlets and /or service requests may try to access a class variable
concurrently.
4. Request attributes Not thread-safe
See the quote below.
5. Session attributes Not thread-safe
Since sessions are scoped at the web application level, hence the same session object can
be accessed concurrently by multiple servlets and their service requests
6. Context attributes Not thread-safe
Since the same context object can be accessed concurrently by multiple servlets and their
service requests

7.2 Identify correct statements about differences between the multi-threaded and single-threaded
servlet models.

multi-thread model servlet:

one servlet instance per registered name


for each servlet request, the server spawns a separate thread which executes the servlet's
service() method
must synchronize access to instance variables

single-thread model servlet:

has a pool of servlet instances per registered name (depending on the server
implementation, the pool size may be configurable or not, and may be as little as one.)
guaranteed by server "that no two threads will execute concurrently in the servlet's
service method"
considered thread-safe and isn't required to synchronize access to instance variables
does not prevent synchronization problems that result from servlets accessing shared
resources such as static variables or objects outside the scope of the servlet (e.g.
ServletContext, HttpSession)
server might end up creating more instances than the system can handle, e.g. each
instance might have its own db connection, hence in total there may be more db
connections than the db server can handle.

Multithread Issue in Servlet 2.3

7.3 Identify the interface used to declare that a servlet must use the single thread model.

interface javax.servlet.SingleThreadModel { // this is an empty "tag" interface }

The use of the SingleThreadModel interface guarantees that only one thread at a time will
execute in a given servlet instances service method. It is important to note that this guarantee
only applies to each servlet instance, since the container may choose to pool such objects.
Objects that are accessible to more than one servlet instance at a time, such as instances of
HttpSession, may be available at any particular time to multiple servlets, including those that

implement SingleThreadModel. Multithreading Issues


A servlet container may send concurrent requests through the service method of the servlet. To
handle the requests the developer of the servlet must make adequate provisions for concurrent
processing with multiple threads in the service method.
An alternative for the developer is to implement the SingleThreadModel interface which requires
the container to guarantee that there is only one request thread at a time in the service method. A
servlet container may satisfy this requirement by serializing requests on a servlet, or by
maintaining a pool of servlet instances. If the servlet is part of a web 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.
For servlets not implementing the SingleThreadModel interface, if the service method (or
methods such as doGet or doPost which are dispatched to the service method of the HttpServlet
abstract class) has been defined with the synchronized keyword, the servlet container cannot use
the instance pool approach, but must serialize requests through it. It is strongly recommended
that developers not synchronize the service method (or methods dispatched to it) in these
circumstances because of detrimental effects on performance.

Thread-safe issue for Request & Response


Implementations of the request and response objects are not guaranteed to be thread safe. This
means that they should only be used within the scope of the request handling thread. References
to the request and response objects must not be given to objects executing in other threads as the
resulting behavior may be nondeterministic.
-- SRV. 2.3.3.3.
Note: Javacamp.org would like to thank reader Andrew Zhou who pointed out a mistake in the
notes and it has been corrected.

The request and response object are not thread safe according to the Servlet Specification 2.3
version. Please refer SRV.2.3.3.3 for more specific information.

Return to top

SECTION 8: THE JAVA SERVER PAGES


(JSP) TECHNOLOGY MODEL
Section 8

8.1 Write the opening and closing tags for the following JSP tag types:
Directive
Declaration

Scriptlet

Expression
8.2 Given a type of JSP tag, identify correct statements about its purpose or use.
8.3 Given a JSP tag type, identify the equivalent XML-based tags.
8.4 Identify the page directive attribute, and its values, that:
Import a Java class into the JSP page
Declare that a JSP page exists within a session

Declare that a JSP page uses an error page

Declare that a JSP page is an error page


8.5 Identify and put in sequence the following elements of the JSP page lifecycle:
Page translation
JSP page compilation

Load class
Create instance
Call jspInit
Call _jspService
Call jspDestroy
8.6 Match correct descriptions about purpose, function, or use with any of the following implicit
objects:
request
response

out
session
config
application
page
pageContext

exception
8.7 Distinguish correct and incorrect scriptlet code for:
A conditional statement;

An iteration statement

Section 8 - The Java Server Pages (JSP)


Technology Model
8.1 Write the opening and closing tags for the following JSP tag types:

1. Directive
2. Declaration
3. Scriptlet
4. Expression

Directives

JSP Directives (Directives are used during the translation phase; all other elements are
used during request processing phase)
<%@ include file={static hltml file or regular jsp file} %> includes file as part of the
translation unit, which is compiled into a servlet; a page may include multiple include
directives
<%@ page {} %> assigns various page-dependent attributes; defaults are given below:
1. language= "java"
2. contentType= "text/html"
3. import= "java.util.Date, java.util.DateFormat" {may have more than one import
assignments via multiple page directives}
4. session= "true" (if set to false, the implicit session variable is not available to scripting
elements)
5. isErrorPage= "false" (set to true if this page is used as an error page, and it will have
the implicit exception variable available to scripting elements)
6. errorPage= "" (no default; page-relative or context-relative URI to redirect to in case
exception thrown)
7. autoFlush= "true" (if false, throws exception when buffer is full)
8. buffer= "8kb" (defines size of buffer; "none" to disable buffering)
9. info= "" (no default; used by server administrative tool as a description of the jsp
page)
10. isThreadSafe= "true" (if set to false, then will use SingleThreadModel)
11. extends= "" (no default; fully qualified classname to extend; class must implement
JspPage or HttpJspPage interface)
<%@ taglib {} %> declares a tag library, containing custom actions, that is used in the
page
1. prefix= "" (mandatory; no default; specifies prefix to use in the action element
names for all actions in the library)
2. uri= "" (mandatory; no default; either a symbolic name for the tag library in the
web.xml file or a page- or context-relative uri for the library's TLD or JAR file)

Declaration

<%! String mystring = new String("hello"); %>


must be a valid java variable declaration; declares instance variables of the JSP
implementation class; thread-safe alternative is to declare variables in scriptlets, so they
are local variables
may also declare methods within a Declaration element
JSP implicit variables are not visible in a declaration element, since they are declared
within the _jspService() method.

Scriptlet

<% if (1+2==true) { %> yippee!! <% } else { %> boohoo!! <% } %>
scriptlet code fragments are combined with code for sending template data between them
to the browser; the combination of all scriptlets in a page must form valid java code
all JSP implicit variables are visible in a scriptlet element

Expresson
<%= 1+2 %> or <%= mystring %>
must be complete valid java expression that results in or can be converted to a string.
all JSP implicit variables are visible in an expression element

8.2 Given a type of JSP tag, identify correct statements about its purpose or use.

Directive - controls translation and compilation phase.


Declaration - declare a java variable or method. No output produced. Class level
declarations.
Scriptlet - valid java statements. No output produced unless out is used
Expression - evaluation of expression to a String and then included in the output

8.3 Given a JSP tag type, identify the equivalent XML-based tags.

<%@ page %> == <jsp:directive.page />


<%! %> == <jsp:declaration> </jsp:declaration>
<% %> == <jsp:scriptlet>> </jsp:scriptlet>
<%= %> == <jsp:expression>> </jsp:expression>

taglib directive doesn't have XML equivalent, it is included in <jsp:root> element as a xmlns
element. <%@taglib uri=http://my.com/my.tld prefix="my" %> will become <jsp:root
xmlns:my=http://my.com/my.tld> </jsp:root> Template text should use <jsp:text> element.

8.4 Identify the page directive attribute, and its values, that:

1. Import a Java class into the JSP page


<%@ page import="java.util.Date" %> (Multiple declarations are separated by comma)
2. Declare that a JSP page exists within a session
<%@ page session="true"%>
3. Declare that a JSP page uses an error page
<%@ page errorPage="errorPage.jsp" %>
4. Declare that a JSP page is an error page
<%@ page isErrorPage="true" %>

8.5 Identify and put in sequence the following elements of the JSP page lifecycle:

1. Page translation
2. JSP page compilation
3. Load class
4. Create instance
5. Call jspInit
6. Call _jspService
7. Call jspDestroy

The above order is already correct.

Basically there are two phases, translation and execution. During the translation phase the
container locates or creates the JSP page implementation class that corresponds to a given JSP
page. This process is determined by the semantics of the JSP page. The container interprets the
standard directives and actions, and the custom actions referencing tag libraries used in the page.
A tag library may optionally provide a validation method to validate that a JSP page is correctly
using the library. A JSP container has flexibility in the details of the JSP page implementation
class that can be used to address quality-of-service --most notably performance--issues.

During the execution phase the JSP container delivers events to the JSP page implementation
object. The container is responsible for instantiating request and response objects and invoking
the appropriate JSP page implementation object. Upon completion of processing, the response
object is received by the container for communication to the client.

8.6 Match correct descriptions about purpose, function, or use with any of the following implicit
objects:

1. request
2. response
3. out
4. session
5. config
6. application
7. page
8. pageContext
9. exception
Purpose, function or use of the implicit objects
Implicit
Type Purpose/Useful methods Scope
Object
request Subclass of The request.getAttribute, setAttribute, request
ServletRequest getParameter, getParameterNames,
getParameterValues
response Subclass of The response page
ServletResponse
out JspWriter Object for writing to the output stream, flush, page
getBuffreSize
session HttpSession created as long as <% page session="false" session
%> is not used. Valid for Http protocol only.
getAttribute, setAttribute
config ServletConfig Specific to a servlet instance. Same as page
Servlet.getServletConfig() getInitParameter,
getInitParameterNames
application ServletContext Available to all Servlets (application wide). application
Provides access to resources of the servlet
engine (resources, attributes, context params,
request dispatcher, server info, URL & MIME
resources).
page Object this instance of the page(equivalent servlet page
instance "this")
pageContext PageContext provides a context to store references to page
objects used by the page, encapsulates
implementation-dependent features, and
provides convenience methods.
exception java.lang.Throwable created only if <%@page page
isErrorPage="true"%>

PageContext provides a number of facilities to the page/component implementor including

a single API to manage the various scoped namespaces


a number of convenience API's to access various public objects
a mechanism to obtain the JspWriter for output
a mechanism to manage session usage by the page
a mechanism to expose page directive attributes to the scripting environment
mechanisms to forward or include the current request to other active components in the
application
a mechanism to handle errorpage exception processing

The methods related to attributes are:

setAttribute(),
getAttribute(),
removeAttribute() - deals page scope
findAttribute(), - looks in all scopes
int getAttributesScope()
getAttributeNamesInScope(int scope)

The following methods provide convenient access to implicit objects:

getOut(),
getException(),
getPage()
getRequest(),
getResponse(),
getSession(),
getServletConfig()
getServletContext()

The following methods provide support for forwarding, inclusion and error handling:

forward(relativeURl),
include(relativeURl),
handlePageException(Exception/Throwable).

8.7 Distinguish correct and incorrect scriptlet code for:

1. A conditional statement;
2. An iteration statement

Conditional Statement

<% if (event.equals("ENTER_RECORD")) { %>


<jsp:include page="enterRecord.jsp" flush=true"/>
<% } else if (event.equals ("NEW_RECORD")) { %>
<jsp:include page="newRecord.jsp" flush="true/>
<% } else { %>
<jsp:include page="default.jsp" flush = true"/>
<% } %>

Iterative Statement
<% Hashtable h = (Hashtable) session.getAttribute("charges");
if (h != null) { %>
<ul>
<%
Enumeration charges = h.keys();
While (charges.hasMoreElements()) {
String proj = (String) charges.nextElement();
Charge ch = (Charge) h.get(proj);
%>
<li>
name = <%= ch.getName() %>
, project = <%= proj %>
, hours = <%= ch.getHours() %>
, date = <%= ch.getDate() %>
<% } %>
</ul>
<% } %>

Return to top

SECTION 9: DESIGNING AND


DEVELOPING REUSABLE WEB
COMPONENTS
Section 9

9.1 Given a description of required functionality, identify the JSP page directive or standard tag in
the correct format with the correct attributes required to specify the inclusion of a Web component
into the JSP page.

Section 9 - Designing and Developing


Reusable Web Components
9.1 Given a description of required functionality, identify the JSP page directive or standard tag
in the correct format with the correct attributes required to specify the inclusion of a Web
component into the JSP page.

Include Directive - Translation-time

<%@ include file="relativeURL" %>


Content is parsed by JSP container.

Include Action - Request-time

<jsp:include page="relativeURL" flush=true|false />


<jsp:param name="" value=""|<%= expression > >

Content is not parsed; it is included in place. In case of dynamic resources the result from the
processing is included.

Return to top

SECTION 10: DESIGNING AND


DEVELOPING JSP PAGES USING
JAVABEAN COMPONENTS
Section 10

10.1 For any of the following tag functions, match the correctly constructed tag, with attributes
and values as appropriate, with the corresponding description of the tag's functionality:
Declare the use of a JavaBean component within the page.
Specify, for jsp: useBean or jsp: getProperty tags, the name of an attribute.

Specify, for a jsp: useBean tag, the class of the attribute.


Specify, for a jsp: useBean tag, the scope of the attribute.
Access or mutate a property from a declared JavaBean.
Specify, for a jsp: getProperty tag, the property of the attribute.

Specify, for a jsp: setProperty tag, the property of the attribute to mutate, and the new
value.
10.2 Given JSP page attribute scopes: request, session, application, identify the equivalent servlet
code.
10.3 Identify techniques that access a declared JavaBean component.

Section 10 - Designing and Developing JSP


pages Using JavaBean Components
10.1 For any of the following tag functions, match the correctly constructed tag, with attributes
and values as appropriate, with the corresponding description of the tag's functionality:

1. Declare the use of a JavaBean component within the page.


2. Specify, for jsp: useBean or jsp: getProperty tags, the name of an attribute.
3. Specify, for a jsp: useBean tag, the class of the attribute.
4. Specify, for a jsp: useBean tag, the scope of the attribute.
5. Access or mutate a property from a declared JavaBean.
6. Specify, for a jsp: getProperty tag, the property of the attribute.
7. Specify, for a jsp: setProperty tag, the property of the attribute to mutate, and the new
value.

<jsp:useBean>
<jsp:useBean id="connection"class="com.myco.myapp.myBean" scope="page" />
- create if bean doesn't exist
<jsp:useBean id="connection" beanName="com.myco.myapp.myBean.ser" />
- create from a serialized object
<jsp:useBean id="connection" type="com.myco.myapp.myBean" />
- Bean should already exist

<jsp:useBean id="name" scope="page|request|session|application" typeSpec />

typeSpec ::= class="className" |


class="className" type="typeName" |
type="typeName" class="className" |
beanName="beanName" type="typeName" |
type="typeName" beanName="beanName" |
type="typeName"
First the container looks for the specified bean in the specified scope (default scope is
page), if it is not there, one will be created. With beanName, you can specify a serialized
file for instantiating the bean from.
class or beanName is required, type is optional.
If class and beanName are not specified (only type is specified), the bean will not be
created, it should already exist in the specified scope.
The specified class should not be an abstract class or an interface and should have a
public no-args constructor. If type is specified, the instantiated class is casted to the type.
Instantiate method is used to create the bean.
jsp:useBean action element can have a non-empty body, e.g. a jsp:setProperty action; the
body will be executed for newly instantiated beans only

<jsp:useBean id="name" scope="page|request|session|application" typeSpec >


body - usually this will be scriptlets or jsp:setProperty actions
</jsp:useBean>

<jsp:getProperty>
<jsp:getProperty name="beanName" property="propName" />

<jsp:setProperty>

<jsp:setProperty name="bean1" property="*" />


-- all request parameters will be set in bean's properties (with matching
names)
<jsp:setProperty name="bean2" property="user " param="username " />
-- request parameter 'username' will be set to 'user' property of the bean
<jsp:setProperty name="bean2" property="user " />
-- request parameter 'user' will be set to 'user' property of the bean
(since no param specified, it is assumed to have the same name as the
property)
<jsp:setProperty name="bean2" property="user " value="me" />
<jsp:setProperty name="bean2" property="user " value="<
%=session.getAttribute("user") %>" />
-- new value can be specified with an expression. If it's an expression no
conversion is performed, else standard conversion is performed.

Note: value cannot be used in conjunction with param

10.2 Given JSP page attribute scopes: request, session, application, identify the equivalent servlet
code.

request - HTTPServletRequest
session - HTTPServletRequest.getSession() : HTTPSession
application - GenericServlet.getServletContext() or
GenericServlet.getServletConfig().getServletContext()

10.3 Identify techniques that access a declared JavaBean component.

A declared JavaBean can also be accessed using: (the name specified in the id attribute of
<jsp:useBean>)

Scriptlets
Expressions
Custom Tags

Return to top
SECTION 11: DESIGNING AND
DEVELOPING JSP PAGES USING
CUSTOM TAGS
Section 11

11.1 Identify properly formatted tag library declarations in the Web application deployment
descriptor.
11.2 Identify properly formatted taglib directives in a JSP page.
11.3 Given a custom tag library, identify properly formatted custom tag usage in a JSP page. Uses
include:
An empty custom tag
A custom tag with attributes

A custom tag that surrounds other JSP code

Nested custom tags

Section 11 - Designing and Developing JSP


pages Using Custom Tags
11.1 Identify properly formatted tag library declarations in the Web application deployment
descriptor.

taglib*, <!ELEMENT taglib (taglib-uri, taglib-location)>


<web-app>
<taglib>
<taglib-uri> http://www.jspinsider.com/jspkit/javascript </taglib-uri>
<taglib-location> /WEB-INF/JavaScriptExampleTag.tld </taglib-location>
</taglib>
</web-app>
11.2 Identify properly formatted taglib directives in a JSP page.

<%@ taglib uri="http://jakarta.apache.org/taglibs/datetime-1.0" prefix="dt" %>


- uri can be defined in web.xml or can be directly pointing to the TLD.
- prefix is used in the jsp to reference the tag. ( local namespace)

11.3 Given a custom tag library, identify properly formatted custom tag usage in a JSP page.
Uses include:

1. An empty custom tag


2. A custom tag with attributes
3. A custom tag that surrounds other JSP code
4. Nested custom tags

An empty custom tag - <msgBean:message/>


A custom tag with attributes - <msgBean:message attrName="value" />
A custom tag that surrounds other JSP code
<msgBean:message> <h1>This is the title</h1> </msgBean:message>
Nested custom tags
<msgBean:message> <helloBean:sayHello/> </msgBean:message>

Return to top

SECTION 12: DESIGNING AND


DEVELOPING A CUSTOM TAG LIBRARY
Section 12

12.1 Identify the tag library descriptor element names that declare the following:
The name of the tag
The class of the tag handler

The type of content that the tag accepts

Any attributes of the tag


12.2 Identify the tag library descriptor element names that declare the following:
The name of a tag attribute
Whether a tag attribute is required

Whether or not the attribute's value can be dynamically specified


12.3 Given a custom tag, identify the necessary value for the bodycontent TLD element for any of
the following tag types:
Empty-tag
Custom tag that surrounds other JSP code

Custom tag that surrounds content that is used only by the tag handler
12.4 Given a tag event method (doStartTag, doAfterBody, and doEndTag), identify the correct
description of the methods trigger.
12.5 Identify valid return values for the following methods:
doStartTag
doAfterBody

doEndTag

PageConext.getOut
12.6 Given a "BODY" or "PAGE" constant, identify a correct description of the constant's use in
the following methods:
doStartTag
doAfterBody

doEndTag
12.7 Identify the method in the custom tag handler that accesses:
A given JSP page's implicit variable

The JSP page's attributes


12.8 Identify methods that return an outer tag handler from within an inner tag handler.

Section 12 - Designing and Developing a


Custom Tag Library
12.1 Identify the tag library descriptor element names that declare the following:

1. The name of the tag <name>


2. The class of the tag handler <tag-class>

3. The type of content that the tag accepts <body-content>

4. Any attributes of the tag


<attribute>
<name>username</name>
<rtexprvalue>true</rtexprvalue>
<required>false</required>
<type>String</type>
</attribute>

<!ELEMENT taglib (tlib-version, jsp-version, short-name,


uri?, display-name?, small-icon?, large-icon?, description?, validator?,
listener*,
tag+) >

<!ELEMENT tag (name, tag-class, tei-class?, body-content?, display-name?,


small-icon?, large-icon?, description?, variable*, attribute*, example?)
>

<!ELEMENT variable ( (name-given | name-from-attribute), variable-


class?, declare?,
scope?, description?) >

<!ELEMENT attribute (name, required? , rtexprvalue?, type?, description?)


>

12.2 Identify the tag library descriptor element names that declare the following:

1. The name of a tag attribute <name>


2. Whether a tag attribute is required <required>
3. Whether or not the attribute's value can be dynamically specified <rtexprvalue>

12.3 Given a custom tag, identify the necessary value for the bodycontent TLD element for any
of the following tag types:

1. Empty-tag empty
2. Custom tag that surrounds other JSP code JSP(default, even if there's no body-content
element)
3. Custom tag that surrounds content that is used only by the tag handler tagdependent

12.4 Given a tag event method (doStartTag, doAfterBody, and doEndTag), identify the correct
description of the methods trigger.

1. doStartTag --Process the start tag for this instance


2. doAfterBody --Process body(re)evaluation - repeat for iteration tag.
3. doEndTag --Process the end tag for this instance. Used to clean up resources and add any
closing tags to the output as necessary
12.5 Identify valid return values for the following methods:

1. doStartTag

2.
3. Tag.EVAL_BODY_INCLUDE,
4. BodyTag.EVAL_BODY_BUFFERED,//for BodyTagSupport class
5. Tag.SKIP_BODY
6. doAfterBody

7.
8. IterationTag.EVAL_BODY_AGAIN,
9. Tag.SKIP_BODY
10. doEndTag

11.
12. Tag.EVAL_PAGE,
13. Tag.SKIP_PAGE
14. PageConext.getOut
- javax.servlet.jsp.JspWriter

12.6 Given a "BODY" or "PAGE" constant, identify a correct description of the constant's use in
the following methods:

1. doStartTag
2. doAfterBody
3. doEndTag

EVAL_BODY_AGAIN
Request the reevaluation of some body. Returned from doAfterBody. For backward
compatibility with JSP 1.1, the value is carefully selected to be the same as, now
deprecated, BodyTag.EVAL_BODY_TAG. Defined in IterationTag.
EVAL_BODY_TAG
Deprecated now. Defined in BodyTag
EVAL_BODY_BUFFERED
Request the creation of new buffer, a BodyContent on which to evaluate the body of this
tag. Returned from doStartTag when it implements BodyTag. This is an illegal return
value for doStartTag when the class does not implement BodyTag. Defined in BodyTag.
EVAL_BODY_INCLUDE
Evaluate body into existing out stream. Valid return value for doStartTag. Defined in Tag.
SKIP_BODY
Skip body evaluation. Valid return value for doStartTag and doAfterBody. Defined in
Tag.
EVAL_PAGE
Continue evaluating the page. Valid return value for doEndTag(). Defined in Tag.
SKIP_PAGE
Skip the rest of the page. Valid return value for doEndTag. Defined in Tag.

doStart doAfterBody doEndTag


EVAL_BODY_INCLUDE All
EVAL_BODY_BUFFERED Body tag only
EVAL_BODY_AGAIN iteration
SKIP_BODY All All
EVAL_BODY_TAG deprecated
EVAL_PAGE All
SKIP_PAGE All

12.7 Identify the method in the custom tag handler that accesses:

1. A given JSP page's implicit variable


2. The JSP page's attributes

A PageContext instance provides access to all the namespaces associated with a JSP page,
provides access to several page attributes, as well as a layer above the implementation details.
The following methods provide convenient access to implicit objects:

getOut(),
getException(),
getPage()
getRequest(),
getResponse(),
getSession(),
getServletConfig()
getServletContext()

The following methods provide support for forwarding, inclusion and error handling:

forward(),
include(),
handlePageException().

The methods related to attributes are:

setAttribute(),
getAttribute(),
removeAttribute() - deals page scope
findAttribute(), - looks in all scopes
int getAttributesScope()
getAttributeNamesInScope(int scope)

Note: TagSupport implements IterationTag which extends Tag. BodyTagSupport implements


BodyTag which extends IterationTag.

getPreviousOut(),
getBodyContent(),
setBodyContent(),
doInitBody()
methods are defined in BodyTagSupport.

12.8 Identify methods that return an outer tag handler from within an inner tag handler.

Tag Tag.getParent()
Tag TagSupport.getParent()
Tag TagSupport.findAncestorWithClass(Tag from, java.lang.Class class) (A
static method)

Return to top

SECTION 13 DESIGN PATTERNS


Section 13

13.1 Given a scenario description with a list of issues, select the design pattern (Value Objects,
MVC, Data Access Object, or Business Delegate) that would best solve those issues.
13.2 Match design patterns with statements describing potential benefits that accrue from the use
of the pattern, for any of the following patterns:
Value Objects
MVC

Data Access Object

Business Delegate

Section 13 Design Patterns


13.1 Given a scenario description with a list of issues, select the design pattern (Value Objects,
MVC, Data Access Object, or Business Delegate) that would best solve those issues.

13.2 Match design patterns with statements describing potential benefits that accrue from the use
of the pattern, for any of the following patterns:

1. Value Objects
2. MVC
3. Data Access Object
4. Business Delegate

Design Patterns
Pattern Description/Benefit/Issues
Reduce network traffic by acting as a caching proxy of a remote object.
Total load on the remote object's remote interface is decreased, because
data represented by the Value Object are cached on the client by the Value
Object instance. All accesses to the properties of the Value Objects are
local, and so those accesses cause no remote method invocations.

Value Objects Decreased latency can improve user response time.


Potential Liability - Stale data. Whenever a value object is backed by a
volatile set of values (such as a stock's price and trading volume, for
example) it should only be treated as a snapshot of those values.

It avoids unnecessary network round-trips by creating one-off transport objects to


group together a set of related attributes needed by a client program,
MVC Clarify design by separating data modeling issues from data display and
user interaction.
Allow the same data to be viewed in multiple ways and by multiple users.
Improve extensibility by simplifying impact analysis.
Improve maintainability by encapsulating application functions behind
well-known APIs, and decreasing code replication ("copy-paste-and-
hack").
Enhance reusability by decoupling application functionality from
presentation.
Make applications easier to distribute, since MVC boundaries are natural
distribution interface points.
Can be used to partition deployment and enable incremental updates.
Facilitate testability by forcing clear designation of responsibilities and
functional consistency.
Enhance flexibility, because data model, user interaction, and data display
can be made "pluggable".

Cleanly separates the roles of data and presentation, allowing multiple types of
client displays to work with the same business information.
Abstract and encapsulate data access mechanisms
Greater deployment flexibility
Resource vendor independence
Resource implementation independence
Data Access
Object Easier migration to CMP
Enhance extensibility
Increase complexity because of a level of indirection

Avoid unnecessary marshalling overhead by implementing dependent objects as


lightweight, persistent classes instead of each as an Enterprise Bean.
Reduce coupling between Web and Enterprise JavaBeans tiers, improve
manageability.
Service exception translation
Simpler, uniform interface hiding the details.
Business Delegate may cache results - this may improve performance
Delegate
Increase complexity because of a level of indirection

A business delegate decouples business components from the code that uses
them. The pattern manages the complexity of distributed component lookup and
exception handling, and may adapt the business component interface to a simpler
interface for use by views.
The following patterns are not required for the certification test.
Application Centralize and aggregate behavior to provide a uniform service layer.
Service
Provide a central location to implement business logic that encapsulates
Business Object and services.
Encapsulate this higher-level business logic in a separate component that
uses the underlying Business Objects and services.
Include all the procedural business logic required to implement different
services in your application and use Data Access Objects when necessary
to deal with persistent data.

Reduce coupling among Business Objects.


Under certain conditions, allow designer to trade off data consistency for
access efficiency. JDBC provides read-only, potentially dirty reads of lists
Bimodal Data of objects, bypassing the functionality, and the overhead, of Entity
Access enterprise beans. At the same time, Entity enterprise beans can still be
used for transactional access to enterprise data. Which mechanism to
select depends on the requirements of the application operation
Composite
Model a network of related business entities
Entity
Composite
Separately manage layout and content of multiple composed views
View
Encapsulate state in a protocol-independent way to be shared throughout
an application.
Avoid using protocol-specific system information outside of its relevant
context.
Object is shared with other parts of the application without coupling the
application to a specific protocol.
Improve reusability, maintainability, extensibility, and testability
Context Object
There is a modest performance hit, because state is transferred from one
object to another.

For example, an HTTP request parameter exists for each field of an HTML form
and a Context Object can store this data in a protocol-independent manner while
facilitating its conversion and validation. Then other parts of the application
simply access the information in the Context Object, without any knowledge of
the HTTP protocol. Any changes in the protocol are handled by the Context
Object, and no other parts of the application need to change.
Facade Coordinate operations between multiple business objects in a workflow.
Provide a layer between clients and subsystems of a complex system.
Shield clients from subsystem components, making the subsystems easier
to use.
Provide a restricted view of data and behavior of one or more business
entities.
There are many categories of Facade patterns, like service facades,
session entity facade, etc.

Session entity facade is an instance of the Facade pattern. It avoids inefficient


remote client access of Entity Beans by wrapping them with a Session Bean and
shares its applicability. Use the Session Facade pattern when you want to provide
a simple interface to a complex subsystem of enterprise beans or when you want
to reduce communication & dependencies between client objects and enterprise
beans.
Allow runtime instantiation of an appropriate subclass of a given interface or
Factory method
superclass based on externally-configurable information.
Avoid unnecessary overhead for read-only data by accessing JDBC API's
directly. This allows an application to retrieve only the attributes that need to be
displayed, instead of finding all of the attributes by primary key when only a few
attributes are required by the client. Typically, implementations of this pattern
Fast-Lane
sacrifice data consistency for performance, since queries performed at the raw
Reader pattern
JDBC level do not "see" pending changes made to business information
represented by Enterprise Beans.

Improve read performance of tabular data.


Provide centralized dispatching of requests, e.g. via a controller servlet.
Enable centralized handling of security, navigation, and presentation
Front formatting
Controller
Centralize view management (navigation, templating, security, etc.) for a Web
application in a single object that handles incoming client requests.
Intercepting
Pre- and post-process application requests
Filter
Page-by-Page Avoid sending unnecessary data to the client by breaking a large collection into
Iterator Pattern chunks for display.
Service Locator Simplify client access to enterprise business services
A class which can have at most one instance
Singleton
For more info, click the left link.
Template The key idea is that there is a basic algorithm we want to stay the same,
Method but we want to let subclasses vary how they do the steps. The Template
Method says to define the algorithm in the parent class, but
implementations of the steps in the subclasses
Transfer Object Transfer business data between tiers
Value Keep client value object attributes in synch with the middle-tier business entity
Messenger information that they represent in a bidirectional fashion.
Value List
Efficiently iterate a virtual list
Handler
View Helper Simplify access to model state and data access logic
More More design patterns, focusing on GOF's 23

A good example of these design patterns can be found from Pet Store Demo project.

There are 200+ classes in this project. See the following list to study how the design pattern has
been used:

A task-specific MVC Application Object ( CatalogWebImpl) to cleanly separate the data


model needed to implement the client display for your task (e.g. the set of JSP pages for
the "Browse the Store Catalog" task)
A Data Access Objects implementation class ( CatalogDAOImpl) to isolate the Fast-Lane
Reader JDBC database access code, and to implement the Page-by-Page Iterator behavior
by skipping over rows from previous pages while fetching data, and returning a page-
sized list of rows for the current page.
Two Value Object classes ( Product, Item) to transfer the respective database query result
rows for products and items queries,
Custom JSP tags ( ProductItemListTag, ProductItemAttributeTag) to implement data
binding and formatting code in a layer that hides these coding details from the JSP page
authors.

Return to top