5.1 Identify the interface and methods 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 requirements on sessionrelated HTML pages.
2. 2
THE FOLLOWING SUN CERTIFIED WEB COMPONENT
DEVELOPER FOR J2EE PLATFORM EXAM OBJECTIVES
COVERED IN THIS CHAPTER:
5.1 Identify the interface and methods 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 requirements on sessionrelated HTML pages.
4. 4
• When a client accesses a web application, they often supply
information that will be used by the application at a later period
during the conversation. If this information could not be retained,
the application would need to ask for the information again. This
is both time-consuming and inefficient.
• A servlet’s session object is used to resolve this issue. Sessions
provide various ways to monitor and maintain client data. In this
chapter, we will address how to:
• Track a client’s session
• Change a session’s data
• Respond to the creation or destruction of a session object and
its attributes
• Invalidate a session
5. 5
Tracking Sessions
• When a client interacts with a server application, that client is
likely to make multiple requests to achieve a particular goal.
Because the HTTP protocol is stateless, it closes its connection
after each request.
• client data stored within a request is available for only a short
period of time.
• For a client object with a longer lifespan, a session is used. A
• session object is usually created when a client makes its first
request to an application.
• It is unique to a client and can exist longer than a single
request or even longer than the life of a client.
• It is an object used to track client-specific data for the duration
of the conversation or a specified period of time.
6. 6
• What distinguishes one session from another is its unique
ID. In fact, the container uses this ID to map an incoming
request to the correct session object, which in turn is
associated to a particular client.
• The actual client information can be transferred by using
one of three session processes:
1. Using hidden form fields
2. Rewriting the URL
3. Using cookies
7. 7
Using Hidden Form Fields
• Transferring information between an HTML form and a
servlet can be done in several ways.
• The most basic procedure is to transfer information back
and forth as data values. A form can contain fields with
client-cached values passed between each request.
• Because this information does not need to be visible to
the client, it is marked by using a field type of hidden
8. 8
Imagine the following web application scenario:
1.A login screen is displayed.
2.The user enters their login name and password.
3.The servlet verifies the information and returns a web page for the client to
utilize the company’s services.
4.The new page stores the client’s login name from the previous servlet.
This information is not visible to the client, but is needed for checkout
purposes.By using hidden HTML values , you can store client data
between servlets to use at a later date. The following HTML code produces
the login screen used for this scenario:
9. 9
• After the user enters their login name and password, they
trigger the request by clicking the submit button. The
servlet then verifies the information and constructs a
response containing the client’s information.
• The following code shows this process. (Pay particularly
close attention to the bold text. It highlights how hidden
values are transferred.)
12. 12
• Tracking each hidden value in each servlet can become
tedious. Unfortunately,as the session persists and information
increases, passing hidden data back and forth can become
taxing.
• The session can persist only through dynamically generated
pages. If there is a need to display static, e-mail, or
bookmarked documents, the session will be lost.
• Hidden value transfers are the least secure method of
maintaining information between pages. Because HTTP
transfers all data as clear text, it can be intercepted, extracted,
and manipulated. If someone were watching the transmission
between client and server, they could easily read information
such as the login ID and password.
13. 13
Rewriting the URL
• Anonymous session tracking can also be done by using a
technique called URL rewriting.
• This approach to session tracking is used when clients do not
accept cookies (URL rewriting is a methodology that
associates a session ID to all URL addresses used
throughout the session.
• Using the ID, a developer can map client-related data to the
session object for that client.
• The ID is temporarily stored until the session has ended. After
the session has ended, the ID and related data are discarded.
14. 14
• Keep in mind that it is important for the session ID to have a
standard name that all containers can recognize.
• The specification defines that name as jsessionid . A
standardized name enables the container to associate
requests to their session objects stored on the server.
• There are two methodologies used to rewrite a URL.
> One approach is to manually adjust the URL to include the session
ID,
> the second approach is to use provided API methods to encode the
URL.
15. 15
Manual URL Rewriting
• Manually rewriting a URL can be done by physically
adding the ID to the constructed URL. How the ID is
stored and accessed from within the URL can vary.
16. 16
In this section, we will show you how to rewrite the URL by
adding a session ID to the URL path. But first, let’s talk about
how the ID is generated.
The goal is to derive a value that is completely random and not
shared. The Remote Method Invocation (RMI) API provides
several methods that help develop such a method.
The common procedure is to create a method that does the
following:
public static String generateSessionID(){
String uid = new java.rmi.server.UID().toString();
return java.net.URLEncoder.encode(uid);
}
17. 17
Now you’re ready to learn how to “rewrite” the URL to contain the
session ID. We’ll begin by revisiting the URL structure:
Request URL = contextPath + servletPath + pathInfo+querystring
Given a request URL of /games/Chess , you can break the pieces
into their defined categories:
Context path:/games
Servlet path: /Chess
Path info: /null
Query string: /null
18. 18
If you had a session ID with the value 567, that ID could be incorporated into
the URL by adding it to the path info section, as follows:
/games/Chess/567
Literally, this can be done by concatenating the session ID to the ACTION
value’s URL. For example:
out.println("<FORM ACTION=’/games/Bingo/"
+ sessionID + "/” Method=’POST’>");
out.println("<INPUT TYPE='submit' VALUE='Bingo'>");
When the button is pressed, the current URL is switched to
/games/Bingo/567. This new servlet page provides the session ID
within the URL, which enables the developer to extract any data
stored from previously accessed servlets. To access the session ID,
use the HttpServletRequest method getPathInfo(). This method
returns extraneous information between the servlet and the query
string.
19. 19
you would expect to have a utility class for writing data
and its associated session ID to a location. The class
should also provide functionality to retrieve the client
data based on a unique session ID.
24. 24
Using Methods to Encode the URL
• Instead of manually generating a session ID and
physically adding it to the URL, the API provides methods
that manage the task for the developer.
• The HttpServletResponse class offers the following two
methods:
• public String encodeURL(java.lang.String url)
• public String encodeRedirectURL(java.lang.String url)
The encodeURL(…) method rewrites the specified URL to include a session ID if needed. If one is
not needed, the method returns the original URL.
An unchanged URL can result from a server that does not support URL rewriting or from a server
that has the feature turned off. As for the semantics of how the URL is encoded, that feature or
technique is server-specific.
25. 25
• The second method is similar to the first in that it, too,
encodes the passed-in URL by adding the session ID. It
differs, however, in when it is used.
• At times there is a need for a servlet to temporarily redirect
a response to a different location.
• This is done by using the HttpServletResponse’s method
sendRedirect(String url). Before calling this method, the URL
should be encoded by using a method specifically designed
to handle URL encoding for a redirected response:
encodeRedirectURL(String url).
• The reason for using a different method is that a redirect
URL is different from a normal URL. For a redirect URL, all
non-ASCII values must be converted to their hexadecimal
values; this includes ampersands and equal Signs
26. 26
The following is an example of a rewritten URL:
http://localhost:8080/servlet/CheckOutServlet jsessionid=4347
To encode links in your URL, you must make slight modifications to the HTML code.
Here is an example of how to rewrite the URL to include an encoded URL in a form:
String urlSession = res.encodeURL("/servlet/CheckOutServlet");
out.println("<FORM ACTION=’" + urlSession + "‘” +“ Method='POST'>");
out.println("<INPUT TYPE='submit' VALUE=’ Exit ‘>");
out.println("</FORM></BODY></HTML>");
If your intent is to encode a URL for a link, you simply include an
encoded
String instead of the standard URL:
out.println(“Click “ + “<A HREF=’”+
res.encodeURL(“/servlet/CheckOutServlet”) + “‘>here</A>”);
27. 27
• In order for the container to encode the URL with a session ID,
three conditions usually exist:
• The browser supports URL encoding.
• The browser does not support cookies.
• The session tracking feature is turned on.
• When using the encodeURL(…) method, the session ID is
stored as a path parameter. As such, you must call
req.getPathInfo() to retrieve the ID value.
You can also access the ID by calling req.getSession() to acquire a handle to the actual
session object (assuming one exists). Using the session instance, the ID value can then be
accessed by calling session.getId().
28. 28
• The servlet can also use the following HttpServletRequest
methods to learn more about the methodology used to
generate the ID, as well as its validity:
• public boolean isRequetedSessionIdFromCookie()
• public boolean isRequestedSessionIdFromURL()
• public boolean isRequestedSessionIdValid()
• These methods validate the session object and its place of
origin. If the session is not valid, the servlet can redirect the
user to a new screen to log in again. If the session ID was
obtained from the URL, the servlet might opt to perform a
different task than if it was obtained from a cookie.
29. 29
Using Cookies
• Another way to perform session tracking is through
persistent cookies.
• Remember, a cookie is an object containing small amounts
of information sent by a servlet to a web browser, then
saved by the browser, and later sent back to the server.
• Because the cookie’s value can uniquely identify a client
and maintain client data, using cookies is an optimal way to
track sessions.
• A cookie is created by using two parameters: a name and a
value. The constructor is as follows:
• public Cookie(String name, String value)
• Unlike a hidden value, which must exist in all servlet pages,
a cookie is added to the servlet’s response object and is
propagated to all servlets accessed during the session.
30. 30
• The servlet specification mandates that the name of the value used to
track the session for a cookie must be called JSESSIONID.
• The ID name must be all uppercase when used within a cookie, but
lowercase when used in URL rewriting.
• A cookie can be added to an HttpServletResponse object in the following
way:
• Cookie cookie = new Cookie(“JSESSIONID”, “567”);
• res.addCookie(cookie);
• If another servlet is interested in accessing this information, it can call the
• getCookies() method of the HttpServletRequest class:
• public Cookie[] getCookies()
• Using our example from the preceding “Rewriting the URL” section, you
• can create a cookie to add the session ID. Listing 6.4 demonstrates how
to use cookies to rewrite the OverviewServlet.
33. 33
Using the HttpSession Object
• The final and most convenient way to handle session data
is to pass an HttpSession object, which implicitly contains
the client’s data, back and forth between all session-
related servlets.
34. 34
Using the HttpSession Object
• Previously, we discussed ways to track the session
object between client/ server requests, where each
example (cookie or URL rewriting) used a database for
persistent storage of session data.
• In this section, the HttpSession object replaces the
database for persistent storage, and uses one of the
methods previously discussed to propagate the session
ID.
• Internally, the container determines the method used to
transmit the session ID between the client and server
(whether it used cookies or URL rewriting).
35. 35
• To access a session object, use the HttpServletRequest
method:
• public HttpSession getSession()
• The method returns the HttpSession object tied to the
client requesting the current servlet. If the object does not
exist, the getSession() method will automatically create a
new HttpSession instance.
• The other method used to access a session object is as
follows:
• public HttpSession getSession(boolean create)
• A true value creates a new session object if one does not
already exist.
• A false value prevents a session object from being
created if one does not exist.
36. 36
• Data is stored to an HttpSession object as attributes:
• public void setAttribute(String name, Object value)
• The setAttribute(…) method binds a Java object to a
specified key name. Another servlet can then use the
HttpSession object and access its data by using the
following method:
• public Object getAttribute(String name)
• The getAttribute(…) method uses the key name to find
and return the associated object.
37. 37
Remember, each application has one ServletContext, and each context has multiple
sessions for each client that accesses the application.
38. 38
• Adding an attribute is as easy as removing one. To
unbind an attribute, call the method:
• public void removeAttribute(String name)
• After this method is invoked on an attribute, it is no longer
accessible by any servlet within the application.
• list all the attributes associated with the current session:
• public Enumeration getAttributeNames()
• The getAttributeNames() method returns an Enumeration
object of all current attributes. If a session has no
attributes, a null value is returned.
• Sometimes there is a need to respond to changes to a
session’s attributes. The servlet API provides several
session listener classes designed specifically for this
purpose. HttpSessionBindingListener
39. 39
HttpSessionBindingListener
• By implementing the HttpSessionBindingListener, your
application can be notified when an object is bound or
unbound to a session object.
• The interface has two primary methods that must be
defined:
• valueBound(HttpSessionBindingEvent event)
• valueUnbound(HttpSessionBindingEvent event)
40. 40
• The valueBound(…) method is called before the object is
made available through the getAttribute(…) method.
• In contrast, the valueUnbound(…) method is called after
the object is no longer available via the getAttribute(…)
method of the HttpSession interface.
• The listener is passed an HttpSessionBindingEvent,
which contains the session object, the name, and the
value of the object either bound or unbound to the
session.
41. 41
• To register session listeners to the container, you must
include the listener tag in the web.xml document.
• For example:
<listener>
<listener-class> ConnectionPoolHandler </listener-class>
</listener>
• The container determines the type of listener defined and
then establishes an abstract link between the session and the
listener.
• When changes occur to the session, the appropriate listener
is notified.
42. 42
Invalidating Sessions
• A session can be invalidated in multiple ways. It can
expire automatically,after a specified or default period of
inactivity, or a servlet can explicitly invalidate a session
through method calls.
• Before learning about these options, it is important to
understand the effects on the application and client when
a session is nullified.
• Basically, all the attribute data is lost.
• If you want to retain session information after it is
invalidated, it should be stored to an external resource
such as a database or a long-term cookie.
43. 43
The session-time tag defines the number of inactive minutes
a session will exist before the server terminates the
object.
The following is sample code for the web.xml file used to
change the default termination period:
<web-app>
<session-config>
<session-timeout>15 </session-timeout>
</session-config>
</web-app>
The servlet specification requires that the timeout value be specified in
whole numbers. Some servers allow the use of negative values to indicate
that sessions should not be terminated
44. 44
• A second approach to modifying the life of a session is to
have individual servlets define the inactive time period before
a session is destroyed.
• The HttpSession interface provides the following methods:
> public void setMaxInactiveInterval(int secs)
> public int getMaxInactiveInterval()
• These methods allow fine-grained control. Instead of
applying a time period to the entire application, you can set
the time to specific servlets.
• The benefit of this approach is that you can customize the
timeout period per user or after certain activities have taken
place, such as a lengthy database lookup.
Notice that the time is measured in seconds rather than minutes
45. 45
• The getMaxInactiveInterval() method returns the value
set. If the set method is not used and the time is set by
using the session-timeout tag, the
getMaxInactiveInterval() method will return the timeout
value defined within the web.xml file.
46. 46
The third approach is pretty abrupt. The
HttpSession interface provides
the following method:
• public void invalidate() throws IllegalStateException
• After a handle to the session is obtained, the invalidate()
method can be called to close the session and unbind all
associated objects.
• If the session is already invalidated, then an
IllegalStateException object is thrown.
47. 47
Now that we’ve covered how to end a session, it is
important for you to understand the best practices
associated to a session’s timeout period.
49. 49
1. Which of the following best describes an example of
URL rewriting?
A. out.println("<INPUT TYPE=hidden NAME='name'
VALUE= BillyBob>");
B. out.println("<FORM ACTION=’/servlet/TestServlet
/BillyBob’ METHOD=POST>");
C. HttpSession session = req.getSession();
D. session.addAttribute(“name”, “BillyBob”);
E. None of the above
50. 50
• 1. B. URL rewriting consists of adding data to the
URL. The receiving servlet can then extract the
additional information to utilize the data.
51. 51
2. Which interface provides the method getSession()?
A. ServletRequest
B. ServletResponse
C. HttpServletResponse
D. HttpServletRequest
52. 52
• 2. D. A session is reliant on HTTP transactions. Because
the application’s communication with the client is through
the HttpServletRequest interface, and the session is not
transmitted back to the client, the session object is obtained
via the HttpServletRequest interface.
53. 53
3. Which of the following methods is used to store
objects into a session object?
A. setData(String name, Object obj)
B. setDataAttribute(String name, Object obj)
C. setAttribute(String name, String obj)
D. setAttribute(String name, Object obj)
54. 54
• 3. D. The setAttribute(String name, Object obj)
method binds
• an object with a related key name to the session object.
The other
• methods are all illegal.
55. 55
4. Which of the following methods is used to expunge a
session object?
A. end()
B. destroy()
C. invalidate()
D. kill()
56. 56
• 4. C. The invalidate() method terminates the
associated session and
• then unbinds any objects bound to it.
57. 57
5. Which of the following is not a valid methodology for
session management?
A. Cookies
B. HttpSession objects
C. Hidden values
D. ServletContext object
58. 58
• 5. D. The ServletContext is associated with the web
application, not with the individual client session.
Consequently, data stored to the context is not unique to
a client.
59. 59
6. The session-timeout tag defines the number of
inactive _________ a session will exist before being
terminated.
A. Milliseconds
B. Seconds
C. Minutes
D. Hours
60. 60
• 6. C. The timeout tag defines the minimum number of
minutes of inactivity that can pass before a session can
be inactive before being terminated by the server.
61. 61
7. Which of the following statements is invalid?
A. The session timeout value determines how long a
session lasts.
B. A session is associated with a client.
C. The setMaxInactiveInterval(…) method is used by the
servlet via the HttpSession object.
D. If a session timeout is not set, the server will
terminate sessions by using a default time value.
62. 62
• 7. A. A session timeout value tells the amount of time
the session will stay alive only during an inactive period,
not its entire life.
63. 63
8. What is the recommended timeout period that a
shopping cart application should have?
A. Short
B. Medium
C. Long
D. Irrelevant
64. 64
• 8. C. Because a client usually collects multiple items
in a cart, a shortlived inactive period could cause
problems and irritation to the user.
• This could result in a loss of business because the user
might not want
• to return or might forget what they already selected.
65. 65
9. Which of the following best describes what is
returned when the getMaxInactiveInterval() method is
called?
A. The default inactive timeout period, in minutes, for a
session to exist before termination.
B. The number of seconds an inactive session can exist
when using the setMaxInactiveInterval(int sec) method.
C. The default inactive timeout period, in seconds, for a
session to exist before termination.
D. It depends on how the server or application handles
the session timeout period.
66. 66
• 9. D. Depending on how the session timeout period is
set, the
• getMaxInactiveInterval() method will return the number of
• seconds that the inactive session will exist before
termination.
67. 67
10. Which of the following is not a valid way to change
the inactive period of a session before the server
terminates the session?
A. <session-timeout>60</session-timeout>
B. setMaxInactiveInterval(500)
C. <session-config>30</session-config>
D. Do nothing
68. 68
• 10. C. The session-config tag requires the session-
timeout tag to
• define the number of minutes a session can be inactive.
As for doing
• nothing, the server usually has a default inactive period
defined
• automatically.
69. 69
11. Which of the following methods is used to retrieve a
bound session object?
A. getBoundObject(String name)
B. getData(String name)
C. getSessionObject(String name)
D. getAttribute(String name)
70. 70
• 11. D. The getAttribute(String name) method returns
the object bound to the session by using the associated
name reference.
71. 71
12. Which of the following is an example of URL
rewriting by using the encodeURL(String url) method?
(Choose all that apply.)
A. http://localhost:8080/servlet/play;jsessionid=567
B. http://localhost:8080/servlet/play
C. http://localhost:8080/servlet/play?jsessionid=567
D. None of the above
72. 72
• 12. A, B. The encodeURL(String url) method encodes
the specified
• URL by including the session ID in it. If encoding is not
needed, the
• method returns the URL unchanged.
73. 73
13. Which of the following methods is called when an
object is removed from a session object?
A. valueUnbound(HttpSessionEvent e)
B. valueUnBound(HttpBindingSessionEvent e)
C. valueUnbound(HttpSessionBindingEvent e)
D. valueUnBound(HttpSession e)
74. 74
• 13. C. The valueUnbound, lowercase b, method is
called when an object
• is unbound from the session object. An
HttpSessionBindingEvent is
• passed to the method containing the session object, and
the name and
• value of the object removed can be gathered from this
event object.
75. 75
14. Which of the following statements is true?
A. The valueBound(…) method is called before the
object is made available through the getAttribute()
method.
B. The valueBound(…) method is called after the object
is made available through the getAttribute() method.
C. The valueBound(…) method is called at different
times depending on the server’s preference.
D. None of the above
76. 76
• 14. A. The servlet specification mandates that the
valueBound(…)
• method should be called before the object is made
available through
• the getAttribute() method.
77. 77
15. Which of the following listeners is called when a
session is destroyed?
A. HttpSessionBindingListener
B. HttpSessionListener
C. HttpSessionChangedListener
D. SessionListener
78. 78
• 15. B. The HttpSessionListener is called when a
session is created and
• destroyed