Sun Certified Web Component Developer Study Guide
Sun Certified Web Component Developer Study Guide
1
Please send your comments to: [email protected]
Authors Note
The following document was put together as a guide to study for the Sun
Certified Web Component Developer Exam. This document is actually a
formatted version of the study notes that were used to study for the certification
exam.
Most of the following document comes straight from the Servlet 2.3 and JSP 1.2
specifications, literally cut and paste!
The intent of this document is to share resources with other Java developers and
should be freely distributed. If this document is used, please feel free to drop the
author a message with your comments.
**Please Note***
With regards to Objective Section 8.5 about the order of events of a Jsp, the first
version of this guide was incorrect. It has been updated thanks to feedback
received from www.javaranch.com.
I appreciate the feedback that I have received up to this point. Remember this
document was intended to filter the important (potentially tested) parts from the
Jsp and Servlet specification and not as an all-encompassing guide on how to
pass every possible question on the exam.
Thanks
Ken Zrobok
SCJP2, SCJD2, SCWCD
[email protected]
2
Please send your comments to: [email protected]
Servlets
The Servlet Model
1.1 For each of the HTTP methods, GET, POST and PUT, identify the
corresponding method in the HttpServlet class.
There is no reason to override the class’s service method since service handles
HTTP requests by dispatching them to handler methods for each type of HTTP
request.
1.2 For each of the HTTP methods, GET, POST and HEAD identify the triggers that
might cause a browser to use the method and identify benefits or functionality of
the method.
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. The information is usually posted from a HTML form.
HTTP GET method retrieves whatever information (in the form of an entity) is
identified by the Request-URI. If the Request-URI refers to a data-producing
process, it is the produced data which shall be returned as the entity in the
response and not the source text of the process, unless that text happens to be
the output of the process.
HTTP HEAD method is a GET request that returns no body in the response, on
the request header fields. The client sends a HEAD request when it wants to see
only the headers of a response, such as Content-Type or Content-Length. The
HTTP HEAD method counts the number of output bytes in the response to set
the Content-Length header accurately. This method can be used for obtaining
meta-information about the entity implied by the request without transferring the
entity-body itself. This method is often used for testing hypertext links for validity,
accessibility, and recent modification.
The servlet container must write the headers before committing the response,
because in HTTP the headers must be sent before the response body.
3
Please send your comments to: [email protected]
1.3 For each of the following operations, identify the interface and method name
that should be used:
Request parameters are strings sent by the client to a servlet container as part of
a request.
When the request is an HttpServletRequest, the attributes are populated from the
URI query string and posted form data. The parameters are stored by the servlet
container as a set of name-value pairs.
Multiple parameter values can exist for any given parameter name. The following
methods of the ServletRequest interface are available to access parameters:
o getParameter
o getParameterNames
o getParameterValues
All form data from both the query string and the post body are aggregated into
the request parameter set. The order of the aggregation puts the query string
data before post body data. For example, if a request is made with a query string
of a=hello and a post body of a=goodbye&a=world, the resulting parameter set
would be ordered a=(hello, goodbye, world).
4
Please send your comments to: [email protected]
Retrieve HTTP request header information
A servlet can access the headers of an HTTP request through the following
methods of the HttpServletRequest interface:
o getHeader
o getHeaders
o getHeaderNames
The getHeader method returns a header given the name of the header. There
can be multiple headers with the same name, e.g. Cache-Control headers, in an
HTTP request.
If there are multiple headers with the same name, the getHeader method returns
the first head in the request. The getHeaders method allows access to all the
header values associated with a particular header name, returning an
Enumeration of String objects.
Headers may contain String representations of int or Date data. The following
convenience methods of the HttpServletRequest interface provide access to
header data in a one of these formats:
o getIntHeader
o getDateHeader
A servlet can set headers of an HTTP response via the following methods of the
HttpServletResponse interface:
o setHeader
o addHeader
The setHeader method sets a header with a given name and value. A previous
header is replaced by the new header. Where a set of header values exist for the
name, the values are cleared and replaced with the new value.
The addHeader method adds a header value to the set with a given name. If
there are no headers already associated with the name, a new set is created.
Headers may contain data that represents an int or a Date object. The following
convenience methods of the HttpServletResponse interface allow a servlet to set
a header using the correct formatting for the appropriate data type:
o setIntHeader
o setDateHeader
5
Please send your comments to: [email protected]
o addIntHeader
o addDateHeader
To be successfully transmitted back to the client, headers must be set before the
response is committed. Headers set after the response is committed will be
ignored by the servlet container.
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.
Returns a PrintWriter object that can send character text to the client.
6
Please send your comments to: [email protected]
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.
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
7
Please send your comments to: [email protected]
public java.lang.Object getAttribute(java.lang.String name)
Returns the object bound with the specified name in this session, or null if
no object is bound under the name
Removes the object bound with the specified name from this session. If
the session does not have an object bound with the specified name, this
method does nothing.
Context
A servlet can bind an object attribute into the context by name. Any attribute
bound into a context is available to any other servlet that is part of the same web
application. The following methods of ServletContext interface allow access to
this functionality:
o setAttribute
o getAttribute
o getAttributeNames
o removeAttribute
o getResource
o getResourceAsStream
8
Please send your comments to: [email protected]
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:
The servlet is constructed, and 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.
ServletContext
Servlets (and JSP pages also) may be given names via server administration or
via a web application deployment descriptor. A servlet instance can determine its
name using ServletConfig.getServletName().
The pathname must begin with a "/" and is interpreted as relative to the current
context root. Use getContext to obtain a RequestDispatcher for resources in
foreign contexts.
ServletRequest
The pathname specified may be relative, although it cannot extend outside the
current servlet context. If the path begins with a "/" it is interpreted as relative to
the current context root. This method returns null if the servlet container cannot
return a RequestDispatcher.
9
Please send your comments to: [email protected]
The difference between this method and
ServletContext.getRequestDispatcher(java.lang.String) is that this method can
take a relative path.
Forward
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.
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.
Include
Includes the content of a resource (servlet, JSP page, HTML file) in the
response. In essence, this method enables programmatic server-side includes.
The ServletResponse object has its path elements and parameters remain
unchanged from the caller's. The included servlet cannot change the response
status code or set headers; any attempt to make a change is ignored.
2.1 Identify the structure of the Web Application and Web Archive file, the name of
the WebApp deployment descriptor and the name of the directories where you
place the following:
Since the context path of an application determines the URL namespace of the
contents of the web application, web containers must reject web applications
defining a context path that is the same, determined case sensitively, as the
context path of a web application already deployed that exposes a potentially
conflicting URL namespace.
10
Please send your comments to: [email protected]
A special directory exists within the application hierarchy named “WEB-INF”.
This directory contains all things related to the application that aren’t in the
document root of the application. The WEB-INF node is not part of the public
document tree of the application. No file contained in the WEB-INF directory may
be served directly to a client by the container. However, the contents of the WEB-
INF directory are visible to servlet code using the getResource() and
getResourceAsStream() method calls on the ServletContext.
The /WEB-INF/web.xml
Deployment descriptor
The /WEB-INF/classes/*
Directory for servlet and utility classes. The classes in this directory are available
to the application class loader.
The /WEB-INF/lib/*.jar
Area for Java ARchive files. These files contain servlets, beans, and other utility
classes useful to the web application. The web application class loader can load
class from any of these archive files. The web application classloader loads
classes from the WEB-INF/classes directory first, and then from library JARs in
the WEB-INF/lib directory. Library JARs are loaded from in the same order as
they appear in the WAR archive entries.
2.2 Match the name with a description of purpose or functionality, for each of the
following deployment descriptor elements:
Servlet instance
11
Please send your comments to: [email protected]
Servlet name
The servlet-name element contains the canonical name of the servlet. Each
servlet name is unique within the web application.
Servlet class
The servlet-class element contains the fully qualified class name of the servlet.
Initialization parameters
The servlet-name element contains the canonical name of the servlet. Each
servlet name is unique within the web application.
The url-pattern element contains the url pattern of the mapping. Must follow the
rules specified in Section 11.2 of the Servlet API Specification.
Example
<servlet>
<servlet-name>catalog</servlet-name>
<servlet-class>com.mycorp.CatalogServlet</servlet-class>
<init-param>
<param-name>catalog</param-name>
<param-value>Spring</param-value>
</init-param>
</servlet>
<servlet-mapping>
12
Please send your comments to: [email protected]
<servlet-name>catalog</servlet-name>
<url-pattern>/catalog/*</url-pattern>
</servlet-mapping>
3.1 Identify the uses for and the interfaces (or classes) and methods to achieve
the following features:
ServletContext
The following methods of the ServletContext interface allow the servlet access to
context initialization parameters associated with a web application through its
deployment descriptor:
o getInitParameter
o getInitParameterNames
ServletContextListener
ServletContextAttributeListener
13
Please send your comments to: [email protected]
Implementations of this interface receive notifications of changes to the attribute
list on the servlet context of a web application. To receive notification events, the
implementation class must be configured in the deployment descriptor for the
web application.
Notification that a new attribute was added to the servlet context. Called
after the attribute is added.
Notification that an existing attribute has been removed from the servlet
context. Called after the attribute is removed.
HttpSessionAttributeListener
Notification that an attribute has been added to a session. Called after the
attribute is added.
14
Please send your comments to: [email protected]
Other Listeners
HttpSessionListener
Implementations of this interface may are notified of changes to the list of active
sessions in a web application. To receive notification events, the implementation
class must be configured in the deployment descriptor for the web application.
HttpSessionActivationListener
Objects that are bound to a session may listen to container events notifying them
that sessions will be passivated and that session will be activated. A container
that migrates session between VMs or persists sessions is required to notify all
attributes bound to sessions implementing HttpSessionActivationListener.
HttpSessionBindingListener
3.2 Identify the WebApp deployment descriptor element name that declares the
following features:
15
Please send your comments to: [email protected]
<!ELEMENT param-value (#PCDATA)>
Example
<web-app>
<context-param>
<param-name>Webmaster</param-name>
<param-value>[email protected]</param-value>
</context-param>
</web-app>
Servlet context listener & Session attribute listeners & Servlet context attribute
listeners
The listener element indicates the deployment properties for a web application
listener bean.
Example
The following example is the deployment grammar for registering two servlet
context lifecycle listeners and an HttpSession listener.
<web-app>
<display-name>MyListeningApplication</display-name>
<listener>
<listener-class>com.acme.MyConnectionManager</listener-class>
</listener>
<listener>
<listener-class>com.acme.MyLoggingModule</listener-class>
</listener>
16
Please send your comments to: [email protected]
<servlet>
<display-name>RegistrationServlet</display-name>
</servlet>
</web-app>
See 3.2
4.1 For each of the following cases, identify correctly constructed code for
handling business logic exceptions and match that code with the correct
statements about the code’s behavior: Return an HTTP error using the sendError
response method; Return and HTTP error using the setStatus method.
Error Pages
If a status code indicating an error is set on the response, the container consults
the list of error page declarations for the web application that use the status-code
syntax and attempts a match. If there is a match, the container serves back the
resource as indicated by the location entry.
The web application may have declared error pages using the exception-type
syntax. In this case the container matches the exception type by comparing the
exception thrown with the list of error-page definitions that use the exception-type
17
Please send your comments to: [email protected]
syntax. A match results in the container serving back the resource indicated in
the location entry. The closest match in the class hierarchy wins.
The error page mechanism described does not intervene when errors occur in
servlets invoked using the RequestDispatcher. In this way, a servlet using the
RequestDispatcher to call another servlets has the opportunity to handle errors
generated in the servlet it calls.
o sendRedirect
o sendError
The sendRedirect method will set the appropriate headers and content body to
redirect the client to a different URL. It is legal to call this method with a relative
URL path, however the underlying container must translate the relative path to a
fully qualified URL for transmission back to the client.
If a partial URL is given and, for whatever reason, cannot be converted into a
valid URL, then this method must throw an IllegalArgumentException.
The sendError method will set the appropriate headers and content body for an
error message to return to the client. An optional String argument can be
provided to the sendError method which can be used in the content body of the
error.
These methods will have the side effect of committing the response, if it has not
already been committed, and terminating it. No further output to the client should
be made by the servlet after these methods are called. If data is written to the
response after these methods are called, the data is ignored.
If data has been written to the response buffer, but not returned to the client (i.e.
the response is not committed), the data in the response buffer must be cleared
and replaced with the data set by these methods. If the response is committed,
these methods must throw an IllegalStateException.
18
Please send your comments to: [email protected]
HttpServletResponse
Sends an error response to the client using the specified status code and
clearing the buffer.
Sends an error response to the client using the specified status clearing
the buffer. The server defaults to creating the response to look like an
HTML-formatted server error page containing the specified message,
setting the content type to "text/html", leaving cookies and other headers
unmodified. If an error-page declaration has been made for the web
application corresponding to the status code passed in, it will be served
back in preference to the suggested msg parameter.
Sets the status code for this response. This method is used to set the
return status code when there is no error (for example, for the status
codes SC_OK or SC_MOVED_TEMPORARILY). If there is an error, and
the caller wishes to invoke an defined in the web application, the
sendError method should be used instead.
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 the RequestDispatcher to forward the request to an error page; specify the
handling declaratively in the deployment descriptor.
19
Please send your comments to: [email protected]
The exception type contains a fully qualified class name of a Java exception
type.
The location element contains the location of the resource in the web application
relative to the root of the web application. The value of the location must have a
leading ‘/’.
Example 1
<web-app>
<error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>
</web-app>
Example 2
<web-app>
<error-page>
<exception-type>java.lang.NumberFormatException</exception-type>
<location>/MyException.html</location>
</error-page>
</web-app>
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.
20
Please send your comments to: [email protected]
Writes an explanatory message and a stack trace for a given Throwable
exception to the servlet log file, prepended by the servlet's name
ServletContext
Writes the specified message to a servlet log file, usually an event log.
The name and type of the servlet log file is specific to the servlet
container.
The name and type of the servlet log file is specific to the servlet
container, usually an event log.
5.1 Identify the interface and method for each of the following:
HttpSession
Provides a way to identify a user across more than one page request or visit to a
Web site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP
client and an HTTP server. The session persists for a specified time period,
across more than one connection or page request from the user. A session
usually corresponds to one user, who may visit a site many times. The server
can maintain a session in many ways such as using cookies or rewriting URLs.
21
Please send your comments to: [email protected]
Retrieve objects from a session object.
Returns the object bound with the specified name in this session, or null if
no object is bound under the name.
HttpSessionBindingListener
If an object was already bound to this session of this name that implements
HttpSessionBindingListener, its HttpSessionBindingListener.valueUnbound
method is called.
If the value passed in is null, this has the same effect as calling
removeAttribute().
HttpSessionListener
Implementations of this interface may are notified of changes to the list of active
sessions in a web application. To receive notification events, the implementation
class must be configured in the deployment descriptor for the web application.
22
Please send your comments to: [email protected]
Invalidate
The session-config element defines the session parameters for this web
application.
The session-timeout element defines the default session timeout interval for all
sessions created in this web application. The specified timeout must be
expressed in a whole number of minutes. If the timeout is 0 or less, the container
ensures the default behavior of sessions is never to time out.
Example
<web-app>
… .
<session-config>
<session-timeout>30</session-timeout>
</session-config>
… ..
</web-app>
5.3 Given that URL-rewriting must be used for session management, identify the
design requirement on session-related HTML pages.
Session tracking through HTTP cookies is the most used session tracking
mechanism and is required to be supported by all servlet containers.
23
Please send your comments to: [email protected]
The container sends a cookie to the client. The client will then return the cookie
on each subsequent request to the server, unambiguously associating the
request with a session. The name of the session tracking cookie must be
JSESSIONID.
URL rewriting involves adding data, a session id, to the URL path that is
interpreted by the container to associate the request with a session. The session
id must be encoded as a path parameter in the URL string. The name of the
parameter must be jsessionid.
http://www.myserver.com/catalog/index.html;jsessioid=1234
o authentication
o authorization
o data integrity
o auditing
o malicious code
o Web site attacks
Although the quality assurances and implementation details may vary, servlet
containers have mechanisms and infrastructure for meeting these requirements
that share some of the following characteristics:
Access control for resources: The means by which interactions with resources
are limited to collections of users or programs for the purpose of enforcing
integrity, confidentiality, or availability constraints.
24
Please send your comments to: [email protected]
Data Integrity: The means used to prove that information has not been modified
by a third party while in transit.
6.2 Identify the deployment descriptor element names, and their structure, that
declare the following:
o a security constraint
o a Web resource
o the login configuration
o a security role
A web resource collection is a set of URL patterns and HTTP methods that
describe a set of resources to be protected. All requests that contain a request
path that matches a URL pattern described in the web resource collection is
subject to the constraint. The container matches URL patterns defined in security
constraints using the same algorithm described in this specification for matching
client requests to servlets and static resources.
A user data constraint describes requirements for the transport layer of the
client server: The requirement may be for content integrity (preventing data
tampering in the communication process) or for confidentiality (preventing
reading while in transit). The container must at least use SSL to respond to
requests to resources marked integral or confidential. If the original request was
over HTTP, the container must redirect the client to the HTTPS port.
25
Please send your comments to: [email protected]
Where there are multiple security constraints specified, the container matches
authentication methods and authorizations to security constraints on a ‘first
match wins’basis.
The user group to which the calling principal belongs is retrieved from its security
attributes. The principal is in the security role only if the principal’s user group
matches the user group to which the security role has been mapped by the
deployer.
26
Please send your comments to: [email protected]
<!ELEMENT user-data-constraint (description?, transport-guarantee)>
NONE means that the application does not require any transport guarantees.
A value of INTEGRAL means that the application requires that the data sent
between the client and server be sent in such a way that it can’t be changed in
transit.
CONFIDENTIAL means that the application requires that the data be transmitted
in a fashion that prevents other entities from observing the contents of the
transmission.
The auth-constraint element indicates the user roles that should be permitted
access to this resource collection. The role-name used here must either
correspond to the role-name of one of the security-role elements defined for this
web application, or be the specially reserved role-name "*" that is a compact
syntax for indicating all roles in the web application. If both "*" and rolenames
appear, the container interprets this as all roles.
If no roles are defined, no user is allowed access to the portion of the web
application described by the containing security-constraint.
The container matches role names case sensitively when determining access.
The realm name element specifies the realm name to use in HTTP Basic
authorization
27
Please send your comments to: [email protected]
The security-role element contains the declaration of a security role which is
used in the security-constraints placed on the web application.
The security-role-ref element defines a mapping between the name of role called
from a Servlet using isUserInRole(String name) and the name of a security role
defined for the web application.
For example, to map the security role reference "FOO" to the security role with
role-name "manager" the syntax would be:
<security-role-ref>
<role-name>FOO</role-name>
<role-link>manager</manager>
</security-role-ref>
In this case if the servlet called by a user belonging to the "manager" security
role made the API call isUserInRole("FOO") the result would be true.
Since the role-name "*" has a special meaning for authorization constraints, its
value is not permitted here.
The role-link element is used to link a security role reference to a defined security
role. The role-link element must contain the name of one of the security roles
defined in the security-role elements.
Example
<web-app>
<display-name>A Secure Application</display-name>
<security-role>
<role-name>manager</role-name>
</security-role>
<servlet>
<servlet-name>catalog</servlet-name>
<servlet-class>com.mycorp.CatalogServlet</servlet-class>
<init-param>
<param-name>catalog</param-name>
<param-value>Spring</param-value>
</init-param>
<security-role-ref>
<role-name>MGR</role-name>
<!-- role name used in code -->
<role-link>manager</role-link>
</security-role-ref>
</servlet>
28
Please send your comments to: [email protected]
<servlet-mapping>
<servlet-name>catalog</servlet-name>
<url-pattern>/catalog/*</url-pattern>
</servlet-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>SalesInfo</web-resource-name>
<url-pattern>/salesinfo/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>manager</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
</web-app>
A web client can authenticate a user to a web server using one of the following
mechanisms:
As part of the request, the web server passes the realm (a string) in which the
user is to be authenticated. The realm string of Basic Authentication does not
have to reflect any particular security policy domain (confusingly also referred to
as a realm). The web client obtains the username and the password from the
user and transmits them to the web server. The web server then authenticates
the user in the specified realm.
29
Please send your comments to: [email protected]
HTTP Digest Authentication
The look and feel of the “login screen”cannot be varied using the web browser’s
built-in authentication mechanisms. This specification introduces a required form
based authentication mechanism which allows a Developer to control the look
and feel of the login screens.
The web application deployment descriptor contains entries for a login form and
error page. The login form must contain fields for entering a username and a
password. These fields must be named ’j_username’and ’j_password’,
respectively.
When a user attempts to access a protected web resource, the container checks
the user’s authentication. If the user is authenticated and possesses authority to
access the resource, the requested web resource is activated and a reference to
it is returned. If the user is not authenticated, all of the following steps occur:
The login form associated with the security constraint is sent to the client and the
URL path triggering the authentication is stored by the container.
The user is asked to fill out the form, including the username and password
fields.
The container attempts to authenticate the user using the information from the
form.
30
Please send your comments to: [email protected]
If authentication fails, the error page is returned using either a forward or a re-
direct, and the status code of the response is set to 401.
If the user is authorized, client is redirected to the resource using the stored URL
path. The error page sent to a user that is not authenticated contains information
about the failure.
Form Based Authentication has the same lack of security as Basic Authentication
since the user password is transmitted as plain text and the target server is not
authenticated.
Form based login and URL based session tracking can be problematic to
implement. Form based login should be used only when sessions are being
maintained by cookies or by SSL session information.
In order for the authentication to proceed appropriately, the action of the login
form must always be j_security_check. This restriction is made so that the login
form will work no matter which resource it is for, and to avoid requiring the server
to specify the action field of the outbound form.
Here is an example showing how the form should be coded into the HTML page:
<form method=”POST”action=”j_security_check”>
<input type=”text”name=”j_username”>
<input type=”password”name=”j_password”>
</form>
If the form based login is invoked because of an HTTP request, the original
request parameters must be preserved by the container for use if, on successful
authentication, it redirects the call to the requested resource.
The form-login-config element specifies the login and error pages that should be
used in form based login. If form based authentication is not used, these
elements are ignored.
The form-login-page element defines the location in the web app where the page
that can be used for login can be found. The path begins with a leading / and is
interpreted relative to the root of the WAR.
The form-error-page element defines the location in the web app where the error
page that is displayed when login is not successful can be found. The path
begins with a leading / and is interpreted relative to the root of the WAR.
31
Please send your comments to: [email protected]
<!ELEMENT form-error-page (#PCDATA)>
Legal values for this element are "BASIC", "DIGEST", "FORM", or "CLIENT-
CERT".
o local variables
o instance variables
o class variables
o request attributes
o session attributes
o context attributes
Number of Instances
In the case where a servlet was deployed as part of an application marked in the
deployment descriptor as distributable, a container may have only one instance
per servlet declaration per VM. If the servlet in a distributable application
implements the SingleThreadModel interface, the container may instantiate
multiple instances of that servlet in each VM of the container.
The use of the SingleThreadModel interface guarantees that only one thread at a
time will execute in a given servlet instance’s 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.
32
Please send your comments to: [email protected]
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.
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.
Thread Safety
References to the request and response objects must not be given to objects
executing in other threads as the resulting behavior may be nondeterministic.
Multiple servlets executing request threads may have active access to a single
session object at the same time. The Developer has the responsibility for
synchronizing access to session resources as appropriate.
33
Please send your comments to: [email protected]
application. The container must reference each listener instance until the last
request is serviced for the web application.
See 7.1
7.3 Identify the interface used to declare that a servlet must use the single thread
model.
SingleThreadModel
Ensures that servlets handle only one request at a time. This interface has no
methods.
If a servlet implements this interface, you are guaranteed that no two threads will
execute concurrently in the servlet's service method. The servlet container can
make this guarantee by synchronizing access to a single instance of the servlet,
or by maintaining a pool of servlet instances and dispatching each new request
to a free servlet.
This interface does not prevent synchronization problems that result from
servlets accessing shared resources such as static class variables or classes
outside the scope of the servlet.
34
Please send your comments to: [email protected]
JSPs
The JSP Model
8.1 Write the opening and closing tags for the following JSP tag types:
directive
declaration
scriptlet
<%scriptlet %>
expression
<%=expression %>
8.2 Given a type of JSP tag identify correct statements about its purpose or use.
o The taglib directive in a JSP page declares that the page uses a
tag library, uniquely identifies the tag library using a URI and
associates a tag prefix that will distinguish usage of the actions in
the library.
35
Please send your comments to: [email protected]
Scripting elements provide glue around template text and actions. There are
three types of scripting elements: declarations, scriptlets and expressions.
Declarations are used to declare variables and methods in the scripting language
used in a JSP page. A declaration should be a complete declarative statement,
or sequence thereof, according to the syntax of the scripting language specified.
Declarations do not produce any output into the current out stream. Declarations
are initialized when the JSP page is initialized and are made available to other
declarations, scriptlets, and expressions.
Scriptlets can contain any code fragments that are valid for the scripting
language specified in the language directive. Whether the code fragment is legal
depends on the details of the scripting language. Scriptlets are executed at
request-processing time. Whether or not they produce any output into the out
stream depends on the code in the scriptlet.
8.3 Given a JSP tag type identify the equivalent XML-based tags.
Directive: page
or
Directive: include
<%@include file=”copyright.html”%>
or
<jsp:directive.include file=”copyright.html”/>
or
36
Please send your comments to: [email protected]
<jsp:declaration>int i=0; </jsp:declaration>
<%
if (Calendar.getInstance().get(Calendar.AM_PM)==Calendar.AM) {
Good Morning
}else {
Good Afternoon
}
%>
or
<jsp:scriptlet>
if (Calendar.getInstance().get(Calendar.AM_PM)==Calendar.AM) {
Good Morning
}else {
Good Afternoon
}
</jsp:scriptlet>
or
8.4 Identify the page directive attributes and its values, that:
<%@page import=”java.util.Enumeration”%>
<%@page session=”true”%>
37
Please send your comments to: [email protected]
declares that a JSP page uses an error page
<%@page errorPage=”myErrorPage.jsp”%>
<%@page isErrorPage=”true”%>
8.5 Identify and put in sequence the following elements of the JSP life-cycle:
o page translation
o JSP compilation
o load class
o create instance
o call jspInit
o call _jspService
o call _jspDestroy
JSP pages are textual components. They go through two phases: a translation
phase, and a request phase. Translation is done once per page. The request
phase is done once per request.
The JSP page is translated to create a servlet class, the JSP page
implementation class that is instantiated at request time. The instantiated JSP
page object handles requests and creates responses.
JSP pages may be translated prior to their use, providing the web application,
with a servlet class that can serve as the textual representation of the JSP page.
The translation may also be done by the JSP container at deployment time or on-
demand as the requests reach an untranslated JSP page.
In the execution phase the container manages one or more instances of this
class in response to requests and other events.
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.
38
Please send your comments to: [email protected]
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.
The translation of a JSP source page into its implementation class can occur at
any time between initial deployment of the JSP page into the JSP container and
the receipt and processing of a client request for the target JSP page.
A JSP page may be compiled into its implementation class plus deployment
information during development. (A JSP page can also be compiled at
deployment time.)
Order of Events
The translation of a JSP source page into its implementation class can occur at
any time between initial deployment of the JSP page into the JSP container and
the receipt and processing of a client request for the target JSP page.
A JSP page can be compiled at development time or wait until deployment time
to compile. During the compilation the JSP page is converted to the page
implementation class (in other words a Servlet).
Once the page is requested the container loads the class and creates and
instance of that class.
The first time the JSP page is requested the jspInit() method is called, and the
request is handled by the _jspService() method.
39
Please send your comments to: [email protected]
When the container is done with the page, the _jspDestroy() method is called.
This is where any cleanup (database connection) may be handled.
_jspDestroy
8.6 Match correct descriptions about purpose, function, or use with any of the
following implicit objects:
request
The request object can be used like the HttpServletRequest parameter of the
service() method of a Servlet.
response
The response object can be used like the HttpServletResponse parameter of the
service() method of a Servlet.
out
The out object represents a JspWriter that will write to the JSP’s output stream.
session
The session object represents a user’s session (HttpSession) created for the
requesting client.
config
The config object represents the servlet config (ServletConfig) that represents
the servlet’s configuration.
application
page
The instance of this page’s implementation class processing the current
request.
pageContext
40
Please send your comments to: [email protected]
exception
The uncaught Throwable that resulted in the error page being invoked.
a conditional statement
<% if (Calendar.getInstance().get(Calendar.AM_PM)==Calendar.AM) {
%>
Good Morning
<%
} else {
%>
Good Afternoon
<%
}
%>
an iteration statement
<%
}
%>
Examples
41
Please send your comments to: [email protected]
Syntax
Examples
Syntax
and
An include directive regards a resource like a JSP page as a static object; i.e. the
bytes in the JSP page are included. An include action regards a resource like a
JSP page as a dynamic object; i.e. the request is sent to that object and the
result of processing it is included.
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.
Examples
42
Please send your comments to: [email protected]
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.
In this case, the body will be invoked if the Bean denoted by the action is
created. Typically, the body will contain either scriptlets or jsp:setProperty tags
that will be used to modify the newly created object, but the contents of the body
are not restricted.
id
The name used to identify the object instance in the specified scope’s
namespace, and also the scripting variable name declared and initialized
with that object reference.
The name specified is case sensitive and shall conform to the current
scripting language variable-naming conventions.
scope
The scope within which the reference is available. The default value is
page . The fully qualified name of the class that defines the
implementation of the object. The class name is case sensitive.
If the class and beanName attributes are not specified the object must be
present in the given scope.
beanName
43
Please send your comments to: [email protected]
The name of a Bean, as expected by the instantiate() method of the
java.beans.Beans class.
type
If unspecified, the value is the same as the value of the class attribute.
Examples
The following two elements set a value from the request parameter values.
Syntax
44
Please send your comments to: [email protected]
Examples
Syntax
10.2 Given JSP attribute scopes: request, session, application, identify the
equivalent servlet code.
Request HttpServletRequest
Session HttpSession
Application ServletContext
The jsp:useBean action is quite flexible; its exact semantics depends on the
attributes given. The basic semantic tries to find an existing object using id and
scope. If the object is not found it will attempt to create the object using the other
attributes.
It is also possible to use this action to give a local name to an object defined
elsewhere, as in another JSP page or in a Servlet. This can be done by using the
type attribute and not providing class or beanName attributes.
At least one of type and class must be present, and it is not valid to provide both
class and beanName. If type and class are present; class must be assignable to
type (in the Java platform sense). For it not to be assignable is a translation-time
error.
The web.xml file can include a map between URIs and TLD resource paths. The
map is described using the taglib element of the Web Application Deployment
descriptor in WEB-INF/web.xml, as described in the Servlet 2.3 spec and in
“http://java.sun.com/j2ee/dtds/web-app_2_3.dtd”.
45
Please send your comments to: [email protected]
A taglib element has two sub-elements: taglib-uri and taglib-location.
<taglib>
The taglib element provides information on a tag library that is used by a JSP
page within the Web Application.
<taglib-uri>
A taglib-uri element describes a URI identifying a tag library used in the
web application.
<taglib-location>
Example
The use of relative URI specifications enables very short names in the taglib
directive. For example:
<taglib>
<taglib-uri>/myPRlibrary</taglib-uri>
<taglib-location>/WEB-INF/tlds/PRlibrary_1_4.tld</taglib-uri>
</taglib>
<%@taglib uri=”/myPRlibrary”prefix=”x”%>
11.3 Given a custom tag library identify properly formatted custom tag usage in a
JSP page. Uses include:
<x:sample />
<x:sample></x:sample>
46
Please send your comments to: [email protected]
a custom tag with attributes
<x:sample>
<x:if>some condition</x:if>
</x:sample>
12.1 Identify the tag library descriptor element names that declare the following:
<tag-class>
<tei-class>
<body-content>
47
Please send your comments to: [email protected]
There are currently three values specified:
tagdependent
JSP
The body of the action contains elements using the JSP syntax.
The body of the action may be empty.
empty
12.2 Identify the tag library descriptor element names that declare the following:
<name>
<required>
<rtexprvalue>
<type>
48
Please send your comments to: [email protected]
Defines the Java type of the attribute’s value. For static values (those
determined at translation time) the type is always java.lang.String. If the
rtexprvalue element is true, that is the value of the nesting attribute may
be calculated from an expression scriptlet during request processing then
the type defines the return type expected from any scriptlet expression
specified as the value of this attribute.
An example is:
<type>java.lang.Object </type>
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
<body-content>
tagdependent
The body of the action is passed verbatim to be interpreted by the
tag handler itself, and is most likely in a different “language”, e.g.
embedded SQL statements. The body of the action may be
empty.
JSP
The body of the action contains elements using the JSP syntax.
The body of the action may be empty.
empty
12.4 Given a tag event method (doStartTag, doAfterBody and doEndTag), identify
the correct description of the methods trigger.
49
Please send your comments to: [email protected]
doStartTag()
doAfterBody()
doEndTag()
If this method returns SKIP_PAGE, the rest of the page is not evaluated and the
request is completed. If this request was forwarded or included from another
page (or Servlet), only the current page evaluation is completed.
pageContext.getOut()
Returns the current JspWriter stream being used for client response.
doStartTag()
doAfterBody()
doEndTag()
SKIP_BODY
50
Please send your comments to: [email protected]
EVAL_BODY_INCLUDE
SKIP_PAGE
EVAL_PAGE
EVAL_BODY_AGAIN
EVAL_BODY_BUFFERED
12.7 Identify the method is the custom tag handler that accesses:
The following methods provide support for forwarding, inclusion and error
handling: forward(), include(), and handlePageException().
PageContext.findAttribute()
51
Please send your comments to: [email protected]
public abstract java.lang.Object findAttribute(java.lang.String name)
Searches for the named attribute in page, request, session (if valid), and
application scope(s) in order and returns the value associated or null.
PageContext.getAttributeNamesInScope()
12.8 Identify methods that return an outer tag from within an inner tag handler.
findAncestorWithClass
Find the instance of a given class type that is closest to a given instance.
This method uses the getParent method from the Tag interface. This
method is used for coordination among cooperating tags.
getParent
Get the parent (closest enclosing tag handler) for this tag handler. This
method is used by the findAncestorWithClass() method in TagSupport.
13.1 Given a scenario description with a list of issues, select the design patters
(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:
ValueObjects
MVC
Data Access Object
Business Delegate
See Below
52
Please send your comments to: [email protected]
Value Objects
Context
Application clients need to exchange data with enterprise beans.
Problem
J2EE applications implement server-side business components as session
beans and entity beans. Session beans represent the business services and
maintain a one-to-one relationship with the client. Entity beans on the other hand
are multi-user, transactional objects representing persistent data. A session bean
provides coarse-grained service methods when implemented per the Session
Façade pattern. Some of the service methods may return data to the client that
invoked the methods. In such cases, the client must invoke the session bean's
get methods multiple times until the client obtains values for all the attribute
values. Every such method call made to the session bean is potentially remote.
Enterprise bean method calls may permeate the network layers of the system
even if the client and the EJB container holding the entity bean are both running
in the same JVM, OS, or physical machine. Some vendors may implement
mechanisms to reduce this overhead by using a more direct access approach.
Forces
J2EE applications implement business components as enterprise bean
components. All access to an enterprise bean is performed via remote interfaces
to the bean. Every call to an enterprise bean is potentially a remote method call
with network overhead.
53
Please send your comments to: [email protected]
The client usually requires more than one attribute value of an enterprise bean.
The client may also need values for the dependent objects of the enterprise
bean. Thus, the client may invoke multiple remote calls to obtain the required
data.
The number of calls made by the client to the enterprise bean impacts network
performance. Chattier applications— those with increased traffic between client
and server tiers— often degrade network performance.
Solution
Use a Value Object to encapsulate the business data. A single method call
is used to send and retrieve the Value Object. When the client requests the
enterprise bean for the business data, the enterprise bean can construct
the Value Object, populate it with its attribute values, and pass it by value
to the client.
Clients usually require more than one value from an enterprise bean. To reduce
the number of remote calls and to avoid the associated overhead, it is best to use
value objects to transport the data from the enterprise bean to its client.
When an enterprise bean uses a value object, the client makes a single remote
method invocation to the enterprise bean to request the value object instead of
numerous remote method calls to get individual attribute values. The enterprise
bean then constructs a new value object instance and copies the attribute values
from its attributes into the newly created value object. It then returns the value
object to the client. The client receives the value object and can then invoke its
accessor (or getter) methods to get the individual attribute values from the value
object. Or, the implementation of the Value Object may be such that makes all
attributes public. Because the value object has been passed by value to the
client, all calls to the value object instance are local calls instead of remote
method invocations.
54
Please send your comments to: [email protected]
When developing an application to support a single type of client, it is sometimes
beneficial to interweave data access logic with interface-specific logic for
presentation and control. Such an approach, however, is inadequate when
applied to enterprise systems that need to support multiple types of clients:
Different applications need to be developed, one to support each type of client
interface.
The duplication efforts are inevitably imperfect. Slowly, but surely, applications
that are supposed to provide the same core functionality evolve into different
systems.
How can an enterprise support multiple types of clients and at the same time
avoid these costs? The following forces influence the solution:
The same enterprise data needs to be accessed when presented in different
views: e.g. HTML, WML, JFC/Swing, XML.
The same enterprise data needs to be updated through different interactions: e.g.
link selections on an HTML page or WML card, button clicks on a JFC/Swing
GUI, SOAP messages written in XML.
55
Please send your comments to: [email protected]
Supporting multiple types of views and interactions should not impact the
components that provide the core functionality of the enterprise application.
A Solution: Use the Model-View-Controller Architecture
The MVC architecture has its roots in Smalltalk, where it was originally applied to
map the traditional input, processing, and output tasks to the graphical user
interaction model. However, it is straightforward to map these concepts into the
domain of multi-tier enterprise applications:
The model represents enterprise data and the business rules that govern access
to and updates of this data. Often the model serves as a software approximation
to a real-world process, so simple real-world modeling techniques apply when
defining the model.
A view renders the contents of a model. It accesses enterprise data through the
model and specifies how that data should be presented. It is the view's
responsibility to maintain consistency in its presentation when the model
changes. This can be achieved by using a push model, where the view registers
itself with the model for change notifications, or a pull model, where the view is
responsible for calling the model when it needs to retrieve the most current data.
56
Please send your comments to: [email protected]
A controller translates interactions with the view into actions to be performed by
the model. In a stand-alone GUI client, user interactions could be button clicks or
menu selections, whereas in a Web application, they appear as GET and POST
HTTP requests. The actions performed by the model include activating business
processes or changing the state of the model. Based on the user interactions and
the outcome of the model actions, the controller responds by selecting an
appropriate view.
Multiple views using the same model. The separation of model and view
allows multiple views to use the same enterprise model. Consequently, an
enterprise application's model components are easier to implement, test, and
maintain, since all access to the model goes through these components.
Easier support for new types of clients. To support a new type of client, you
simply write a view and controller for it and wire them into the existing enterprise
model.
Problem
Many real-world J2EETM applications need to use persistent data at some point.
For many applications, the persistent storage is implemented with different
mechanisms, and there are marked differences in the APIs used to access these
different persistent storage mechanisms. Other applications may need to access
data that resides on a different system. For example, the data may reside on a
mainframe, an LDAP repository, a B2B service, a credit card bureau, and so
forth.
Applications can use the JDBCTM API to access data residing in an RDBMS. The
JDBC API enables standard access and manipulation of data in a persistent
storage, such as a relational database. JDBC enables J2EE applications to use
SQL statements, which are the standard means for accessing RDBMS tables.
However, even within an RDBMS environment, the actual syntax and format of
the SQL statements may vary depending on the particular database product.
57
Please send your comments to: [email protected]
There is even greater variation with different types of persistent storage. Access
mechanisms, supported APIs, and features vary drastically when comparing a
relational type of persistent storage such as RDBMS to other types of persistent
stores, such as Object Oriented Databases (OODBMS), file system-based ISAM
databases, or simply flat files. Applications that need to access data from a
legacy or disparate system (for example, a mainframe, CORBA service or B2B
service) are often required to use APIs that may be proprietary. Such disparate
data sources offer challenges to the application and can potentially create a tight
integration between application code and integration code. When business
components— entity beans, session beans and even presentation components
like servlets and JSPTM)— need to access a data source, they can use the
appropriate API to achieve connectivity and manipulate the data source. But,
including the connectivity and data access code within these components
introduces a tight coupling between the components and the data source
implementation. Such code dependencies in the components makes it difficult
and tedious to migrate the application from one type of data source to another.
When the data source changes, the components need to be changed to handle
the new type of data source.
Forces
Components such as bean-managed entity beans, session beans and
servlets/JSP need to retrieve and store information from persistent stores and
other data sources like legacy systems, B2B, LDAP, and so forth.
Persistent storage APIs vary depending on the product vendor. Other data
sources may have APIs that are non-standard and/or proprietary. These APIs
and their capabilities also vary depending on the storage type (RDBMS,
OODBMS, XML documents, flat files, and so forth). There is a lack of uniform
APIs to address the requirements to access such disparate systems.
Components accessing legacy systems to retrieve and store data is typically
done using proprietary APIs.
Solution
Use a Data Access Object to abstract and encapsulate all access to the
data source. The Data Access Object manages the connection with the data
source to obtain and store data.
The Data Access Object (DAO) is the primary object of this pattern. The DAO
implements the access mechanism required to work with the data source. The
data source could be a persistent store like an RDBMS, an external service like a
B2B exchange, a repository like an LDAP database or a business service
accessed via CORBA IIOP or low-level sockets. The business component that
relies on the DAO object uses the simpler interface exposed by the DAO for its
clients. The DAO completely hides the data source implementation details from
its clients. Because the interface exposed by the DAO to clients does not change
when the underlying data source implementation changes, this pattern allows the
58
Please send your comments to: [email protected]
DAO to adapt to different storage schemes without affecting its clients or
business components. Essentially, the DAO acts as an adapter between the
component and the data source.
Business Delegate
Context
The system exposes the entire business service API to its clients, often across a
network.
Problem
Presentation-tier components interact directly with business services. This direct
interaction exposes the underlying implementation details of the business service
API to the presentation tier. As a result, the presentation-tier components are
vulnerable to changes in the implementation of the business services: when the
implementation of the business services change, the exposed implementation
code in the presentation tier must change too.
Lastly, exposing the service APIs directly to the client forces the client to deal
with the networking issues associated with the distributed nature of EJBTM
technology.
Forces
Presentation-tier clients need access to business services.
Device clients (including rich clients) need access to the business service.
Business service API may change as business requirements evolve.
Goal should be to minimize coupling between presentation-tier clients and the
business service API, thus hiding the underlying implementation details of the
service, such as lookup and access.
Solution
Use a Business Delegate to reduce coupling between presentation-tier
clients and business services. The Business Delegate hides the underlying
implementation details of the business service, such as lookup and access
details of the EJB architecture.
59
Please send your comments to: [email protected]
The Business Delegate acts as a client-side business abstraction; it provides an
abstraction for, and thus hides the implementation of the business services.
Using a Business Delegate reduces the coupling between presentation-tier
clients and the system's business services. Depending on the implementation
strategy, the Business Delegate may shield clients, from possible volatility in the
implementation of the business service API. Potentially, this reduces the number
of changes that must be made to the presentation-tier client code when the
business service API or its underlying implementation changes. However, the
Business Delegate may still require modification if the underlying business
service API changes.
Often, developers are skeptical when a design goal such as abstracting the
business layer causes additional upfront work in return for future gains. However,
using this pattern or its strategies results in only a small amount of additional up
front work and provides considerable benefits. The main benefit is hiding the
details of the underlying service. For example, the client can become transparent
to naming and lookup services. The Business Delegate also handles the
exceptions from the business services such as EJB exceptions, JMS exceptions
and so on. The Business Delegate may intercept such service level exceptions
and generate application level exceptions instead. Application level exceptions
are easier to handle by the clients, and may be user friendly. These gains
present a compelling reason to use the pattern.
Another benefit is that the delegate may cache results. Caching results can
significantly improve performance, because it limits unnecessary and potentially
costly round trips over the network.
A Business Delegate uses a component called the Lookup Service. The Lookup
Service is responsible for hiding the underlying implementation details of the
business service lookup code. The Lookup Service may be written as part of the
delegate, but we recommend that it be implemented as a separate component,
as outlined in the Service Locator [SJC] pattern.
When the Business Delegate is used with a Session Façade, typically there is a
1-1 relationship between the two. This 1-1 relationship exists because logic that
might have been encapsulated in a Business Delegate relating to its interaction
with multiple business services (creating a 1-many relationship) will often be
factored back into a Session Façade.
Finally, it should be noted that this pattern could be used to reduce coupling
between other tiers, not simply the presentation and the business tiers.
60
Please send your comments to: [email protected]