SCWCD Study Notes
SCWCD Study Notes
SCWCD Study Notes
No claims are made about the accuracy of this document and no responsibility is taken for any errors. The exam
objectives below are quoted, ‘as is’ from Sun Microsystems web site. This document can be used and distributed as
long as the purpose is not commercial.
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 1 of 40
SUN CERTIFIED WEB COMPONENT DEVELOPER FOR
J2EE[tm] PLATFORM OBJECTIVES
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.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.
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.
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
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
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 2 of 40
• 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
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.
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.
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 3 of 40
• 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.
7.3 Identify the interface used to declare that a servlet must use the single thread model.
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
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 4 of 40
• page
• pageContext
• exception
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.
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.
11.1 Identify properly formatted tag library declarations in the Web application deployment descriptor.
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
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
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 5 of 40
• 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.
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
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 6 of 40
1. The Servlet Model
1.1. Identify corresponding method in HttpServlet class for each of the following HTTP methods:
1.1.1. GET: public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
1.1.2. POST: public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
1.1.3. PUT: public void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
1.2. GET, POST and HEAD
1.2.1. Identify triggers that might cause a browser to use:
1.2.1.1. GET: (a) typing url directly into a browser, (b) clicking on a hyperlink, (c) submitting html
form with ‘method=get’ or no method attribute
1.2.1.2. POST: (a) submitting html form with ‘method=post’
1.2.1.3. HEAD: (a) may be used by a browser to check modification time for purposes of caching
1.2.2. Identify benefits or functionality of:
1.2.2.1. GET:
1.2.2.1.1. designed for getting information (e.g. document, chart, results of query)
1.2.2.1.2. can include a query string (some servers limit this to about 240 characters) for sending
information to server
1.2.2.1.3. requested page can be bookmarked
1.2.2.2. POST:
1.2.2.2.1. designed for posting information (e.g. credit card #, info to be stored in a db)
1.2.2.2.2. passes all its data (of unlimited length) to server directly over the socket connection as
part of its http request body
1.2.2.2.3. posts cannot be bookmarked or, in some cases, even reloaded
1.2.2.2.4. hides sensitive information from server log by including it in the message body instead
of the url query string
1.2.2.3. HEAD:
1.2.2.3.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.
1.2.2.3.2. The service() method treats HEAD requests specially. It calls doGet with a modified
response object, which suppresses any output but retains headers.
1.3. For each of the following operations, identify the interface and method name that should be used:
1.3.1. Retrieve HTML form parameters from the request:
1.3.1.1. Enumeration ServletRequest.getParameterNames() - returns empty enum if no parameters
1.3.1.2. String ServletRequest.getParameter(String name) - returns null if does not exist
1.3.1.3. String[] ServletRequest.getParameterValues(String name) - returns null if does not exist
1.3.2. Retrieve a servlet initialization parameter:
1.3.2.1. Enumeration ServletConfig.getInitParameterNames() - returns empty enum if no init
parameters
1.3.2.2. String ServletConfig.getInitParameter(String name) - returns null if does not exist
1.3.3. Retrieve HTTP request header information:
1.3.3.1. Enumeration HttpServletRequest.getHeaderNames() - returns empty enum if no headers
1.3.3.2. String HttpServletRequest.getHeader(String name) - returns null if does not exist
1.3.3.3. Enumeration HttpServletRequest.getHeaders(String name) - returns empty enum if no headers
1.3.3.4. long getDateHeader(String name) - returns -1 if does not exist
1.3.3.5. int getIntHeader(String name) - returns -1 if does not exist
1.3.4. Set an HTTP response header; set the content type of the response
1.3.4.1. void HttpServletResponse.setHeader(String name, String value) - if header already exists,
overwrites its value
1.3.4.2. void HttpServletResponse.setIntHeader(String name, int value)
1.3.4.3. void HttpServletResponse.setDateHeader(String name, long date)
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 7 of 40
1.3.4.4. void HttpServletResponse.addHeader(String name, String value) - if header already exists,
adds an additional value
1.3.4.5. void HttpServletResponse.addIntHeader(String name, int value)
1.3.4.6. void HttpServletResponse.addDateHeader(String name, long date)
1.3.4.7. void HttpServletResponse.setContentType(String type) – if calling getWriter(), then
setContentType should be called first
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 8 of 40
1.4.1.21.String HttpServletRequest.getServletPath() - returns servlet path and name, but no extra path
info
1.4.1.22.HttpSession HttpServletRequest.getSession(boolean create)
1.4.1.23.HttpSession HttpServletRequest.getSession() - calls getSession(true)
1.4.2. Session (Interface: HttpSession)
1.4.2.1. Enumeration HttpSession.getAttributeNames() - returns empty enumeration if no attributes;
IllegalStateException if session invalidated
1.4.2.2. Object HttpSession.getAttribute(String name) - returns null if no such object
1.4.2.3. void HttpSession.setAttribute(java.lang.String name, java.lang.Object value)
1.4.2.4. void HttpSession.removeAttribute(java.lang.String name)
1.4.2.5. String HttpSession.getId() - returns unique session identifier assigned by servlet container
1.4.2.6. long HttpSession.getLastAccessedTime() - time when client last sent a request associated
with this session
1.4.2.7. int HttpSession.getMaxInactiveInterval() - returns number of seconds this session remains
open between client requests; -1 if session should never expire
1.4.2.8. void HttpSession.setMaxInactiveInterval(int interval)
1.4.3. Context (Interface: ServletContext)
1.4.3.1. Enumeration getAttributeNames() - Returns an Enumeration containing the attribute names
available within this servlet context.
1.4.3.2. Object getAttribute(String name) - Returns the servlet container attribute with the given
name, or null if there is no attribute by that name.
1.4.3.3. void setAttribute(String name, java.lang.Object object) - Binds an object to a given attribute
name in this servlet context.
1.4.3.4. void removeAttribute(String name) - Removes the attribute with the given name from the
servlet context.
1.4.3.5. ServletContext getContext(String uripath) - Returns a ServletContext object that corresponds
to a specified URL on the server.
1.4.3.6. String getInitParameter(String name) - Returns a String containing the value of the named
context-wide initialization parameter, or null if does not exist.
1.4.3.7. Enumeration getInitParameterNames() - Returns names of the context's initialization
parameters as Enumeration of String objects
1.4.3.8. int getMajorVersion() - Returns the major version of the Java Servlet API that this servlet
container supports.
1.4.3.9. int getMinorVersion() - Returns the minor version of the Servlet API that this servlet
container supports.
1.4.3.10.String getMimeType(String file) - Returns the MIME type of the specified file, or null if the
MIME type is not known.
1.4.3.11.RequestDispatcher getNamedDispatcher(String name) - Returns a RequestDispatcher object
that acts as a wrapper for the named servlet.
1.4.3.12.RequestDispatcher getRequestDispatcher(String path) - Returns a RequestDispatcher object
that acts as a wrapper for the resource located at the given path.
1.4.3.13.String getRealPath(String path) - Returns a String containing the real path for a given virtual
path.
1.4.3.14.java.net.URL getResource(String path) - Returns a URL to the resource that is mapped to a
specified path.
1.4.3.15.InputStream getResourceAsStream(String path) - Returns the resource located at the named
path as an InputStream object.
1.4.3.16.String getServerInfo() - Returns the name and version of the servlet container on which the
servlet is running.
1.5. For each of the following life-cycle method, identify its purpose and how and when it is invoked:
1.5.1. public void init() throws ServletException:
1.5.1.1. called after server constructs the servlet instance and before the server handles any requests
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 9 of 40
1.5.1.2. depending on the server and web app configuration, init() may be called at any of these times:
(a) when server starts, (b) when the servlet is first requested, just before the service() method is
invoked, (c) at the request of the server administrator
1.5.1.3. 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.
1.5.1.4. 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.
1.5.1.5. servlet cannot be placed into service if init method throws ServletException or does not return
within a server-defined time period
1.5.1.6. init() can only be called once per servlet instance; so would still need to synchronize access to
class variables
1.5.2. public void service() throws ServletException, IOException:
1.5.2.1. called by the servlet container to allow the servlet to respond to a request.
1.5.2.2. this method is only called after the servlet's init() method has completed successfully.
1.5.2.3. servlets typically run inside multithreaded servlet containers that can handle multiple requests
concurrently. developers must be aware to synchronize access to any shared resources such as
files and network connections, as well as the servlet's class and instance variables.
1.5.3. public void destroy():
1.5.3.1. called after the servlet has been taken out of service and all pending requests to the servlet
have been completed or timed out
1.5.3.2. 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
1.5.3.3. calling super.destroy() causes GenericServlet.destroy() to write a note to the log that the servlet
is being destroyed
1.5.3.4. destroy()called once per servlet instance; destroy() not called if server crashes, so should save
state (if needed) periodically after servicing requests
1.5.4. Note: servlet reloading
1.5.4.1. 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.
1.5.4.2. 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.
1.6. Use a RequestDispatcher to include or forward to a Web resource
1.6.1. include:
1.6.1.1. public void include(ServletRequest request, ServletResponse response) throws
ServletException, IOException
1.6.1.2. Includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence,
this method enables programmatic server-side includes.
1.6.1.3. 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. If the included element
requires information on its own path elements, it’s available in request attributes
(javax.servlet.include.request_uri, context_path etc)
1.6.1.4. The included servlet cannot change the response status code or set headers; any attempt to
make a change is ignored.
1.6.1.5. The request and response parameters must be the same objects as were passed to the calling
servlet's service method.
1.6.1.6. The included resource must use the same output mechanism (e.g. PrintWriter or
ServletOutputStream) as the caller’s
1.6.1.7. Information can be passed to target using attached query string or using request attributes set
with setAttribute() method.
1.6.1.8. include can be called at any time, even after the flush is called on the response.
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 10 of 40
1.6.2. forward:
1.6.2.1. public void forward(ServletRequest request, ServletResponse response) throws
ServletException, IOException
1.6.2.2. 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.
1.6.2.3. 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.
1.6.2.4. 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.
1.6.2.5. The request and response parameters must be the same objects as were passed to the calling
servlet's service method.
1.6.2.6. Information can be passed to target using attached query string or using request attributes set
with setAttribute() method.
1.6.2.7. 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().
1.6.3. Note: to get a request dispatcher object:
1.6.3.1. public javax.servlet.RequestDispatcher ServletRequest.getRequestDispatcher(String path) -
path may be relative, and cannot extend outside current servlet context
1.6.3.2. public javax.servlet.RequestDispatcher ServletRequest.getNamedDispatcher(String name) -
name is the registered name in web.xml file
1.6.3.3. ServletContext also supports these methods, but its getRequestDispatcher method accepts only
absolute paths, and not relative paths. Use the request’s methods, ServletContext method may
be depracted in future.
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 11 of 40
2.2.1. servlet instance:
2.2.1.1. <servlet> {servlet-name, servlet-class, init-param, etc.} </servlet>
2.2.1.2. declares a servlet instance; included within <web-app> </web-app> tags
2.2.2. servlet name:
2.2.2.1. <servlet-name></servlet-name>
2.2.2.2. registers the servlet under a specific name
2.2.3. servlet class:
2.2.3.1. <servlet-class></servlet-class>
2.2.3.2. contains the fully qualified class name of the servlet
2.2.4. initialization parameters:
2.2.4.1. <init-param> {param-name, param-value} </init-param>
2.2.4.2. defines values that can be set at deployment time and read at run-time via
ServletConfig.getInitParameter(String name)
2.2.5. url to named servlet mapping
2.2.5.1. <servlet-mapping> <servlet-name> helloServlet </servlet-name> <url-pattern> /hello.html
</url-pattern> </servlet-mapping> this maps http://server:port/context_root/hello.html to
the helloServlet servlet.
2.2.5.2. zero or more mappings may be defined per web app
2.2.5.3. 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
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 12 of 40
3.3.1.2. interfaces (or classes): javax.servlet.ServletContextAttributeListener
3.3.1.3. methods: void
attributeAdded/attributeRemoved/attributeReplaced(ServletContextAttributeEvent e)
3.3.1.4. webapp deployment descriptor element name: <listener> <listener-class> {fully qualified class
name} </listener-class> <listener>
3.3.1.5. 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.
3.4. HttpSession Attribute Listener
3.4.1.1. purpose: An object that implements the HttpSessionAttributeListener interface is notified when
a session attribute is added, removed or replaced
3.4.1.2. interfaces (or classes): javax.servlet.http.HttpSessionAttributeListener
3.4.1.3. methods: void attributeAdded/attributeRemoved/attributeReplaced(HttpSessionBindingEvent
e)
3.4.1.4. webapp deployment descriptor element name: <listener> <listener-class> {fully qualified class
name} </listener-class> <listener>
3.4.1.5. 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.
3.5. Http Session Listener
3.5.1.1. purpose: An object that implements the HttpSessionListener interface is notified when a
session is created or destroyed in its web app context
3.5.1.2. interfaces (or classes): javax.servlet.http.HttpSessionListener
3.5.1.3. methods:
3.5.1.3.1. void sessionCreated(HttpSessionEvent e)
3.5.1.3.2. void sessionDestroyed(HttpSessionEvent e) - called when session is destroyed
(invalidated)
3.5.1.4. webapp deployment descriptor element name: <listener> <listener-class> {fully qualified class
name} </listener-class> <listener>
3.5.1.5. 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.
3.6. Http Session Activation Listener
3.6.1.1. 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.
3.6.1.2. mothods:
3.6.1.2.1. void sessionWillPassivate(HttpSessionEvent e) - session is about to move; it will already
be out of service when this method is called
3.6.1.2.2. void sessionDidActivate(HttpSessionEvent e) - session has been activated on new
server; session will not yet be in service when this method is called
3.6.1.3. webapp deployment descriptor element name:
<listener> <listener-class> {fully qualified class name} </listener-class> <listener>
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 13 of 40
4.1.1.4. calling setStatus() on an error leaves a servlet with the responsibility of generating the error
page
4.1.1.5. must be called before the response is committed, otherwise call is ignored
4.1.2. return an http error using sendError
4.1.2.1. public void HttpServletResponse.sendError(int statusCode[, String statusMessage]) throws
IllegalStateException, IOException
4.1.2.2. 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)
4.1.2.3. with the two argument version of this method, the server may include the status message in the
error page, depending on the server implementation
4.1.2.4. must be called before response body is committed, else throws IllegalStateException
4.2. Given a set of business logic exceptions, identify the following:
4.2.1. configuring deployment descriptor for error handling
4.2.1.1. <web-app> …
<error-page>
<error-code>404</ error-code>
<location> /404.html </location>
</error-page> …
</web-app>
4.2.1.2. 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
4.2.1.3. the value of location must begin with ‘/’, is treated as based in the context root, and must refer
to a resource within the context
4.2.1.4. <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
4.2.2. configuring deployment descriptor for exception handling
4.2.2.1. <web-app> …
<error-page>
<exception-type> javax.servlet.ServletException</ exception-type >
<location> /servlet/ErrorDisplay </location>
</error-page> …
</web-app>
4.2.2.2. 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
4.2.2.3. <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
4.2.2.4. 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)
4.2.2.5. a ServletException may be created with a message and a “root cause”, both optional, e.g.
{ throw new ServletException(“execution interrupted”, InterruptedException); }
4.2.2.6. public Throwable ServletException.getRootCause() returns the root cause exception
4.2.2.7. javax.servlet package also defines a subclass of ServletException called
UnavailableException(String msg[, int seconds]), which causes server to take servlet out of
service
4.2.3. using RequestDispatcher to forward to an error page: see section 1.6 above
4.3. Identify the method used for the following:
4.3.1. writing a message to the Web App log:
4.3.1.1. void log(String msg) - Writes the specified message to a servlet log file, usually an event log.
4.3.1.2. 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.
4.3.1.3. these are methods are available in GenericServlet and ServletContext
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 14 of 40
4.3.2. writing a message and an exception to the Web App log:
4.3.2.1. public void GenericServlet.log(String msg, Throwable t)
4.3.2.2. writes the given message and the Throwable’s stack trace to a servlet log; exact output format
and location of log are server specific
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 15 of 40
5.2.4. timeout can be overridden for a specific session by calling HttpSession.setMaxInactiveInterval(int
secs) – negative value indicates session should never time out.
5.2.5. session may expire manually, when it is explicitly invalidated by a servlet by calling invalidate()
5.2.6. a server shutdown may or may not invalidate a session, depending on the capabilities of the server
5.2.7. 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
5.3.1. For a servlet to support session tracking via URL rewriting, it has to rewrite every local URL before
sending it to the client.
5.3.2. public String HttpServletResponse.encodeURL(String url)
5.3.3. public String HttpServletResponse.encodeRedirectURL(String url)
5.3.4. 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.
5.3.5. 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.
5.4. Note: Using Cookies:
5.4.1.1. To send a cookie to a client: {Cookie cookie = new Cookie(“name”, “value”);
res.addCookie(cookie);}.
5.4.1.2. To retrieve cookies: {Cookie[] cookies = req.getCookies();}
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 16 of 40
<role-name>ceo</role-name>
</auth-constraint> if no role-name, then not viewable by any user;
if role-name = “*” then viewable by all roles
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint> optional, indicates SSL security
</security-constraint>
<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. For each of the following authentication types, identify the correct definition of its mechanism
6.3.1. BASIC
6.3.1.1. 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.
6.3.1.2. Disadvantage: provides no confidentiality, no integrity, and only the most basic authentication.
6.3.1.3. Disadvantage: Transmitted passwords are encoded using easily reversable Base64 encoding,
unless additional SSL encryption employed.
6.3.1.4. Disadvantage: plus, passwords are often stored on server in clear text
6.3.1.5. Advantage: very easy to set up; useful for low-security environments, e.g. subscription-based
online newspaper
6.3.2. DIGEST
6.3.2.1. variation to BASIC scheme; instead of transmitting password over network directly, digest of
password used instead, 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.
6.3.2.2. Advantage: transactions are somewhat more secure than with basic authentication, since each
digest is valid for only a single uri request and nonce value.
6.3.2.3. Disadvantage: server must still maintain a database of the original passwords
6.3.2.4. Disadvantage: digest authentication is not supported by very many browsers
6.3.3. FORM
6.3.3.1. 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.
6.3.3.2. 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 <form-error-page>
6.3.3.3. Advantage: allows users to enter your site through a well-designed, descriptive and friendly
login page
6.3.3.4. Disadvantage: similar to BASIC, password is transmitted in clear text, unless SSL used
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 17 of 40
6.3.3.5. Disadvantage: similar to BASIC, no standard logout mechanism (calling session.invalidate()
may work for FORM, but no guarantees), would need to close browser
6.3.3.6. Disadvantage: 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
6.3.3.7. Disadvantage: similar to BASIC, relies on server to authenticate, so only captures username
and password, not custom fields e.g. PIN #.
6.3.4. CLIENT-CERT
6.3.4.1. BASIC, even with SSL encryption, does not ensure strong client authentication since anyone
could have guessed or gotten hold of client’s username and password
6.3.4.2. 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.
6.3.4.3. 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
6.3.4.4. 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.
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 18 of 40
Section 8: The JSP Model
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
a) Directive – controls translation and compilation phase.
b) Declaration – declare a java variable or method. No output produced. Class
level declarations.
c) Scriptlet – valid java statements. No output produced unless out is used
d) 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.
a) <%@ page …%> == <jsp:directive.page …/>
b) <%! …%> == <jsp:declaration> … </jsp:declaration>
c) <% …%> == <jsp:scriptlet> … </jsp:scriptlet>
d) <%= …%> == <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>
8.4 Identify the page directive attribute, and its values, that:
• Import a Java class into the JSP page <%@ page import=”java.util.Date” %>
(Multiple declarations are separated by comma)
• Declare that a JSP page exists within a session <%@ page session=”true”%>
• Declare that a JSP page uses an error page <%@ page errorPage=”errorPage.jsp” %>
• 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:
• Page translation
• JSP page compilation
• Load class
• Create instance
• Call jspInit
• Call _jspService
• Call jspDestroy
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
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 19 of 40
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:
• request
• response
• out
• session
• config
• application
• page
• pageContext
• exception
PageContext provides a number of facilities to the page/component author and page 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 compo-nents
in the application
• a mechanism to handle errorpage exception processing
a) 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”/>
<% } %>
b) 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>
<%}%>
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 21 of 40
• Include Directive - Translation-time
<%@ include file=”relativeURL” %>
Content is parsed by JSP container.
<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
•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” />
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 22 of 40
<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.
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()
A declared JavaBean can also be accessed using: (the name specified in the id attribute of <jsp:useBean>)
Scriptlets
Expressions
Custom Tags
11.1 Identify properly formatted tag library declarations in the Web application deployment descriptor.
11.3 Given a custom tag library, identify properly formatted custom tag usage in a JSP page. Uses include:
• 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>
• Nested custom tags
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 23 of 40
<msgBean:message> <helloBean:sayHello/> </msgBean>
12.1 Identify the tag library descriptor element names that declare the following:
• The name of the tag <name>
• The class of the tag handler <tag-class>
• The type of content that the tag accepts <body-content>
• Any attributes of the tag
<attribute>
<name>username</name>
<rtexprvalue>true</rtexprvalue>
<required>false</required>
<type>String</type>
</attribute>
12.2 Identify the tag library descriptor element names that declare the following:
• The name of a tag attribute - <name>
• Whether a tag attribute is required - <required>
• 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:
• Empty-tag - empty
• Custom tag that surrounds other JSP code – JSP (default, even if there’s no body-content element)
• 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.
doStart – Process the start tag for this instance
doAfterBody – Process body (re)evaluation – repeat for iteration tag.
doEndTag – Process the end tag for this instance. Used to clean up resources and add any closing tags to
the output as necessary
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 24 of 40
• doAfterBody – IterationTag.EVAL_BODY_AGAIN, Tag.SKIP_BODY
• doEndTag – Tag.EVAL_PAGE, Tag.SKIP_PAGE
• PageContext.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:
• doStartTag
• doAfterBody
• 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.
12.7 Identify the method in the custom tag handler that accesses:
• A given JSP page's implicit variable
• 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() and getServletContext().
The following methods provide support for forwarding, inclusion and error handling:
forward(), include(), and handlePageException().
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 25 of 40
findAttribute(), - looks in all scopes
int getAttributesScope() and 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)
Pattern Description/Benefit/Issues
Value •Reduce network traffic by acting as a caching proxy of a remote object.
Objects •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.
•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.
MVC •Clarifies design by separating data modeling issues from data display and user interaction.
•Allows the same data to be viewed in multiple ways and by multiple users.
•Improves extensibility by simplifying impact analysis.
•Improves maintainability by encapsulating application functions behind well-known APIs, and decreasing code
replication (“copy-paste-and-hack”).
•Enhances reusability by decoupling application functionality from presentation.
•Makes applications easier to distribute, since MVC boundaries are natural distribution interface points.
•Can be used to partition deployment and enable incremental updates.
•Facilitates testability by forcing clear designation of responsibilities and functional consistency.
•Enhances flexibility, because data model, user interaction, and data display can be made “pluggable”.
Data •Greater deployment flexibility
Access •Resource vendor independence
Object •Resource implementation independence
•Easier migration to CMP
•Enhanced extensibility
•Increased complexity because of a level of indirection
Business •Reduced coupling, improved manageability.
Delegate •Service exception translation
•Simpler, uniform interface hiding the details.
•Delegate may cache results – this may improve performance
•Increased complexity because of a level of indirection
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 26 of 40
Front •Provides centralized dispatching of requests, e.g. via a controller servlet.
Component •Enables centralized handling of security, navigation, and presentation formatting
Façade •Provides a layer between clients and subsystems of a complex system.
•Shields clients from subsystem components, making the subsystems easier to use
Factory •Handles requests for object creation
Singleton •A class which can have at most one instance
Template •The key idea is that there is a basic algorithm we want to stay the same, but we want to let subclasses vary how they
Method do the steps. The Template Method says to define the algorithm in the parent class, but implementations of the steps
in the subclasses
Bimodal •Under certain conditions, allows designer to trade off data consistency for access efficiency. JDBC provides read-
Data only, potentially dirty reads of lists of objects, bypassing the functionality, and the overhead, of Entity enterprise
Access 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
Session •Being an instance of the Facade pattern, this pattern shares its applicability. In the context of J2EE application
Entity development, use the Session Facade pattern when you want to provide a simple interface to a complex subsystem of
Façade enterprise beans or when you want to reduce communication & dependencies b/w client objects and enterprise beans.
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 27 of 40
Servlet API
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 28 of 40
init(ServletConfig) Called by the servlet container to indicate to a servlet that the servlet
is being placed into service.
destroy() Called by the servlet container to indicate to a servlet that the servlet
is being taken out of service.
service(ServletRequest, ServletResponse) Called by the servlet container to allow the servlet to respond to a
Servlet
request.
ServletConfig getServletConfig() Returns a ServletConfig object, which contains initialization and
startup parameters for this servlet.
String getServletInfo Returns information about the servlet, such as author, version, and
copyright.
String getInitParameter(String) Returns a String containing the value of the named initialization
parameter, or null if the parameter does not exist.
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.
ServletConfig ServletContext getServletContext() Returns a reference to the ServletContext in which the caller is
executing.
String getServletName() Returns the name of this servlet instance. The name may be provided
via server administration, assigned in the web application
deployment descriptor, or for an unregistered (and thus unnamed)
servlet instance it will be the servlet's class name.
String getInitParameter(String) Returns a String containing the value of the named context-wide
initialization parameter, or null if the parameter does not exist.
Enumeration getInitParameterNames() Returns the names of the context's initialization parameters as an
Enumeration of String objects, or an empty Enumeration if
the context has no initialization parameters.
Object getAttribute(String) Returns the servlet container attribute with the given name, or null
if there is no attribute by that name.
setAttribute(String, Object) Binds an object to a given attribute name in this servlet context.
removeAttribute(String) Removes the attribute with the given name from the servlet context.
Enumeration getAttributeNames() Returns an Enumeration containing the attribute names available
within this servlet context.
ServletContext
log(String) Writes the specified message to a servlet log file, usually an event
log.
log(String, Throwable) Writes an explanatory message and a stack trace for a given
Throwable exception to the servlet log file.
ServletContext getContext(String uripath) Returns a ServletContext object that corresponds to a specified
URL on the server. The given path must be absolute (beginning with
"/") and is interpreted based on the server's document root.
String getRealPath(String path) Returns a String containing the real path for a given virtual path.
java.net.URL getResource(String path) Returns a URL to the resource that is mapped to a specified path.
The path must begin with a "/" and is interpreted as relative to the
current context root.
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 29 of 40
java.net.URL getResource(String path) This method allows the servlet container to make a resource
available to servlets from any source. Resources can be located on a
local or remote file system, in a database, or in a .war file. The
resource content is returned directly, so be aware that requesting a
.jsp page returns the JSP source code. Use a
RequestDispatcher instead to include results of an execution.
This method has a different purpose than
java.lang.Class.getResource, which looks up resources
based on a class loader. This method does not use class loaders.
java.io.InputStream Returns the resource located at the named path as an
ServletContext
getResourceAsStream(String path) InputStream object.
RequestDispatcher Returns a RequestDispatcher object that acts as a wrapper for the
getRequestDispatcher(String path) resource located at the given path. The resource can be dynamic or
static. 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. This
method returns null if the ServletContext cannot return a
RequestDispatcher.
RequestDispatcher Returns a RequestDispatcher object that acts as a wrapper for the
getNamedDispatcher(String name) named servlet.
Object getAttribute(String) Returns the value of the named attribute as an Object, or null if
no attribute of the given name exists.
setAttribute(String, Object) Stores an attribute in this request.
removeAttribute(String) Removes an attribute from this request.
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.
String getParameter(String) Returns the value of a request parameter as a String, or null if
the parameter does not exist.
String[] getParameterValues(String) Returns an array of String objects containing all of the values the
given request parameter has, or null if the parameter does not exist.
Enumeration getParameterNames() Returns an Enumeration of String objects containing the
ServletRequest names of the parameters contained in this request.
ServletInputStream getInputStream() Retrieves the body of the request as binary data using a
ServletInputStream. Either this method or getReader() may be called
to read the body, not both.
BufferedReader getReader() Retrieves the body of the request as character data using a
BufferedReader. The reader translates the character data
according to the character encoding used on the body.
Either this method or getInputStream() may be called to read the
body, not both.
RequestDispatcher Returns a RequestDispatcher object that acts as a wrapper for
getRequestDispatcher(String path) the resource located at the given path. A RequestDispatcher
object can be used to forward a request to the resource or to include
the resource in a response. The resource can be dynamic or static.
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 30 of 40
RequestDispatcher The pathname specified may be relative, although it cannot extend
getRequestDispatcher(String path) 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.
The difference between this method and ServletContext’s method is
that this method can take a relative path.
String getRemoteAddr() Returns the Internet Protocol (IP) address of the client that sent the
request.
String getRemoteHost() Returns the fully qualified name of the client that sent the request, or
the IP address of the client if the name cannot be determined.
String getServerName() Returns the host name of the server that received the request.
int getServerPort() Returns the port number on which this request was received.
String getProtocol() Returns the name and version of the protocol the request uses in the
ServletRequest
form protocol/majorVersion.minorVersion, for example, HTTP/1.1.
String getScheme() Returns the name of the scheme used to make this request, for
example, http, https, or ftp.
boolean isSecure() Returns a boolean indicating whether this request was made using a
secure channel, such as HTTPS.
String getContentType() Returns the MIME type of the body of the request, or null if the
type is not known.
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.
String getCharecterEncoding() Returns the name of the character encoding used in the body of this
request.
setCharecterEncoding(String) Overrides the name of the character encoding used in the body of
this request.
ServletOutputStream getOutputStream() 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
PrintWriter getWriter() 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 method, which must be
called before calling this method for the charset to take effect.
Calling flush() on the PrintWriter commits the response.
ServletResponse Either this method or getOutputStream may be called to write the
body, not both.
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.
setContentLength(int) Sets the length of the content body in the response. In HTTP servlets,
this method sets the HTTP Content-Length header.
boolean isCommitted() Returns a boolean indicating if the response has been committed. A
commited response has already had its status code and headers
written.
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 31 of 40
reset() Clears any data that exists in the buffer as well as the status code and
headers. If the response has been committed, this method throws an
IllegalStateException.
int getBufferSize() Returns the actual buffer size used for the response. If no buffering is
used, this method returns 0.
setBufferSize(int) Sets the preferred buffer size for the body of the response.
This method must be called before any response body content is
ServletResponse written; if content has been written, this method throws an
IllegalStateException.
flushBuffer() Forces any content in the buffer to be written to the client. A call to
this method automatically commits the response, meaning the status
code and headers will be written.
resetBuffer() Clears the content of the underlying buffer in the response without
clearing headers or status code. If the response has been committed,
this method throws an IllegalStateException.
init() A convenience method which can be overridden so that there's no
need to call super.init(config).
log(String) Writes the specified message to a servlet log file, prepended by the
abstract class servlet's name.
GenericServlet log(String, Throwable) Writes an explanatory message and a stack trace for a given
implements Servlet, Throwable exception to the servlet log file, prepended by the
ServletConfig, servlet's name.
Serializable abstract service() Called by the servlet container to allow the servlet to respond to a
request.
This method is declared abstract so subclasses, such as
HttpServlet, must override it.
String getHeader(String) 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.
Enumeration getHeaders(String) Returns all the values of the specified request header as an
Enumeration of String objects. 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.
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.
HttpServletRequest int getIntHeader(String) 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.
long getDateHeader(String) 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. If the request did
not have a header of the specified name, this method returns -1.
Cookie getCookies() Returns an array containing all of the Cookie objects the client sent
with this request, or null if no cookies sent.
HttpSession getSession() Returns the current session associated with this request, or if the
request does not have a session, creates one.
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 32 of 40
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.
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.
requestURI = contextPath + servletPath + pathInfo
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 "".
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.
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.
String getPathTranslated() Returns any extra path information after the servlet name but before
the query string, and translates it to a real path.
String getQueryString() Returns the query string that is contained in the request URL after
the path.
String getMethod() Returns the name of the HTTP method with which this request was
made, for example, GET, POST, or PUT.
HttpServletRequest String getAuthType() Returns the name of the authentication scheme used to protect the
servlet. All servlet containers support BASIC_AUTH,
FORM_AUTH, and CLIENT_CERT_AUTH and may support
DIGEST_AUTH. If the servlet is not authenticated null is
returned.
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.
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.
boolean isUserInRole(String role) Returns a boolean indicating whether the authenticated user is
included in the specified logical "role". Roles and role membership
can be defined using deployment descriptors. If the user has not been
authenticated, the method returns false.
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.
boolean isRequestedSessionIdValid() Checks whether the requested session ID is still valid.
boolean Checks whether the requested session ID came in as a cookie.
isRequestedSessionIdFromCookie()
boolean Checks whether the requested session ID came in as part of the
isRequestedSessionIdFromURL() request URL.
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 33 of 40
addCookie(Cookie) Adds the specified cookie to the response. This method can be called
multiple times to set more than one cookie.
addHeader(String name, String value) Add a response header with the given name and String value /
addIntHeader(String name, int value) integer value / date value respectively. These methods allow
addDateHeader(String name, long value) response headers to have multiple values.
setHeader(String name, String value) Set a response header with the given name and String value / integer
setIntHeader(String name, int value) value / date value respectively. If the header had already been set, the
setDateHeader(String name, long value) new value overwrites the previous one. The containsHeader
method can be used to test for the presence of a header before setting
its value.
setStatus(int sc) 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 error-page defined in the
web applicaion, the sendError method should be used instead.
If this method is called after the response is committed, the call is
ignored.
sendError(int sc) Sends an error response to the client using the specified status
sendError(int sc, java.lang.String msg) clearing the buffer. The server defaults to creating the response to
look like an HTML-formatted server error page, 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
HttpServletRespons preference to the suggested msg parameter.
e 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.
sendRedirect(java.lang.String location) 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.
String encodeURL(java.lang.String url) Encodes the specified URL by including the session ID in it, or, if
encoding is not needed, returns the URL unchanged.
For robust session tracking, all URLs emitted by a servlet should be
run through this method. Otherwise, URL rewriting cannot be used
with browsers which do not support cookies.
String encodeRedirectURL(String url) Encodes the specified URL for use in the sendRedirect method
or, if encoding is not needed, returns the URL unchanged.
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.
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 34 of 40
Object getAttribute(String) Returns the object bound with the specified name in this session, or
null if no object is bound under the name.
setAttribute(String, Object) Binds an object to a given attribute name in this session. If an object
of the same name is already bound to the session, the object is
replaced.
After this method executes, and if the new object implements
HttpSessionBindingListener, the container calls
HttpSessionBindingListener.valueBound.
If an object was already bound to this session of this name that
implements HttpSessionBindingListener, its
HttpSessionBindingListener.valueUnbound method is
called.
removeAttribute(String) Removes the attribute with the given name from the session. After
this method executes, and if the object implements
HttpSessionBindingListener, the container calls
HttpSessionBindingListener.valueUnbound.
Enumeration getAttributeNames() Returns an Enumeration of String objects containing the
names of all the objects bound to this session.
HttpSession String getId() Returns a string containing the unique identifier assigned to this
session.
long getCreationTime() Returns the time when this session was created
long getLastAccessedTime() Returns the last time the client sent a request associated with this
session
int getMaxInactiveInterval() Returns the maximum time interval, in seconds, that the servlet
container will keep this session open between client accesses. After
this interval, the servlet container will invalidate the session. The
maximum time interval can be set with the
setMaxInactiveInterval method. A negative time indicates
the session should never timeout.
setMaxInactiveInterval(int) Specifies the time, in seconds, between client requests before the
servlet container will invalidate this session. A negative time
indicates the session should never timeout.
invalidate() Invalidates this session then unbinds any objects bound to it.
isNew() Returns true if the client does not yet know about the session or if
the client chooses not to join the session. For example, if the server
used only cookie-based sessions, and the client had disabled the use
of cookies, then a session would be new on each request.
abstract class public service(ServletRequest, Dispatches client requests to the protected service method.
HttpServlet extends ServletResponse) There's no need to override this method.
GenericServlet protected service(HttpServletRequest, Receives standard HTTP requests from the public service method
HttpServletResponse) and dispatches them to the doXXX methods defined in this class.
Eventhough this There's no need to override this method.
class is abstract it doGet(HttpServletRequest, Should be safe and idempotent (repeatable)
provides empty HttpServletResponse) Override to service GET requests. HEAD requests are also satisfied
implementations of since doHead internally uses this method with a specialized
all methods. response.
Typically servlets doPost(HttpServletRequest, Need not be safe or idempotent.
extending this class HttpServletResponse) Override to service POST requests.
would override one doPut(), doDelete(), doHead(), doTrace(), These methods are not common and service the corresponding
of the doXXX doOptions() requests.
methods. long getLastModified() Returns the time the HttpServletRequest object was last modified
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 35 of 40
forward(ServletRequest, Forwards a request from a servlet to another resource (servlet, JSP
ServletResponse) 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
RequestDispatcher
before the forward.
include(ServletRequest, ServletResponse) 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.
SingleThreadModel No methods This is a ‘marker’ interface
ServletContext contextInitialized(ServletContextEvent) Implementations of this interface receive notifications about changes
Listener to the servlet context of the web application they are part of. To
receive notification events, the implementation class must be
contextDestroyed(ServletContextEvent) configured in the deployment descriptor for the web application.
ServletContext attributeAdded Implementations of this interface receive notifications of changes to
AttributeListener (ServletContextAttributeEvent) the attribute list on the servlet context of a web application. To
attributeRemoved receive notification events, the implementation class must be
(ServletContextAttributeEvent) configured in the deployment descriptor for the web application.
attributeReplaced
(ServletContextAttributeEvent)
HttpSession sessionCreated(HttpSessionEvent) Implementations of this interface are notified of changes to the list of
Listener active sessions in a web application. To receive notification events,
the implementation class must be configured in the deployment
sessionDestroyed(HttpSessionEvent)
descriptor for the web application.
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 36 of 40
Legend:
? – Optional (0 or 1)
* – Any number (0 - n)
+ – 1 or more (1 - n)
No following character – Required (1)
<!ELEMENT web-app
(icon?, display-name?, description?, distributable?,
filter*,
filter-mapping*,
resource-env-ref*,
resource-ref*,
env-entry*,
ejb-ref*,
ejb-local-ref*)>
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 37 of 40
Example 1
<web-app>
<context-param>
<param-name>Webmaster</param-name>
<param-value>[email protected]</param-value>
</context-param>
<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>
<servlet-name>catalog</servlet-name>
<url-pattern>/catalog/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<mime-mapping>
<extension>pdf</extension>
<mime-type>application/pdf</mime-type>
</mime-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
<error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>
</web-app>
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 38 of 40
Example 2
<web-app>
<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> <!-- role name in security-role-->
</security-role-ref>
</servlet>
<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>
<security-role>
<role-name>manager</role-name>
</security-role>
</web-app>
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 39 of 40
http://www.javaprogrammingworld.com
Study Notes for Sun Certified Web Component Developer for J2EE Platform
Page 40 of 40