You are on page 1of 8

F0101

TOPIC TITLE: Session Management

SPECIFIC OBJECTIVES:

At the end of the topic session, the students are expected to:

Cognitive :

1. Describe the purpose of session management.


2. Explain the Session API.
3. Describe the cookies implementation of session management.
4. Discuss the Cookie API.
5. Develop a Web application that uses session management.

Affective:
1. Participate in group activities.
2. Be attentive to the teacher’s lectures and demonstrations.
3. Participate in class and group discussions.

Psychomotor:
1. Develop a web application that demonstrates the use of Session
and Cookie objects.

MATERIALS/EQUIPMENTS:

o OHP
o Topic slides

TOPIC PREPARATION:

o Read about session management and cookie implementation.


o It is imperative for the instructor to incorporate various kinds of
teaching strategies while discussing the suggested topics. The
instructor may use the suggested learning activities below to
facilitate a thorough and creative discussion of the topic.
o Prepare the slides to be presented in class.

TOPIC PRESENTATION:

The topic will revolve around Session Management, Session API, Cookie
API and Cookie Implementation.

This will be the suggested flow of discussion for Session Management.

1. Describe the purpose of session management.


2. Explain the Session API.
3. Describe the cookies implementation of session management.
4. Discuss the Cookie API.

Session Management * Property of STI


Page 1 of 8
F0101

Session Management Session Management


Page 1 of 11

Java Enterprise Edition Programming


The Web container provides a mechanism to store session information
for a particular user. We said that HTTP is a stateless protocol. Each
Session Management request and response message connection is independent of any other.
This is significant because from one request to another request, (from the
The Web container provides a mechanism

to store session information for a
same user) the HTTP server forgets the previous request. Therefore, the
particular user.
Web container must create a mechanism to store session information for
Each client is given a unique ID that is

used by the Web container to identify the a particular user.
session object for that user.

Each client is given a unique ID that is used by the Web container to


identify the session object for that user. The Servlet specification
mandates that the Web container must support session objects, which
store attributes that are unique to a specific client but exist across
multiple HTTP requests.

Session Management * Property of STI


Page 1 of 11 Each activity-specific control method must store attributes, name-value
pair, that are used by other requests within the session. For example, in
the BookStoreServlet, the servlet retrieves the form data, the data must
be stored in an object for later use. The Servlet specification provides a
way to store attributes in the session scope. Any control method can
access an attribute that has already been set by processing a previous
request.

[Session Management, Page 1 of 11]

Session API Session API


Page 2 of 11

Java Enterprise Edition Programming


The Servlet specification provides an HttpSession interface that allows
you to store session attributes.
Session API

 The Servlet specification provides an


HttpSession interface that allows you to
store session attributes.

javax.servlet.http

<<interface>> <<interface>>
HttpServlet
request HttpServletRequest response HttpServletSession

service getSession(create:boolean)
getID() : String
doGet getSession()
isNew() : Boolean
doPost
getAttribute(name) : Object
setAttribute(name, value)
removeAttribute(name)

MyServlet

Figure 1: Session API

Session Management * Property of STI


Page 2 of 11

Figure 1 – Session API

This session object allows you to store, retrieve and remove attributes.
The servlet has access to the session object through the getSession()
method of the HttpServletRequest object. The API is represented above.

public interface HttpSession

Provides a way to identify a user across more than one page request or
visit to a Web site and to store information about that user.

The servlet container uses this interface to create a session between an


HTTP client and an HTTP server. The session persists for a specified
time period, across more than one connection or page request from the
user. A session usually corresponds to one user, who may visit a site
many times. The server can maintain a session in many ways, such as

Session Management * Property of STI


Page 2 of 8
F0101

using cookies or rewriting URLs.

This interface allows servlets to:

• View and manipulate information about a session, such as the


session identifier, creation time, and last accessed time.
• Bind objects to sessions, allowing user information to persist
across multiple user connections.

When an application stores an object in or removes an object from a


session, the session checks whether the object implements
HttpSessionBindingListener. If it does, the servlet notifies the object that
it has been bound to or unbound from the session. Notifications are sent
after the binding methods complete. For session that are invalidated or
expired, notifications are sent after the session has been invalidated or
expired.

When a container migrates a session between VMs in a distributed


container setting, all session attributes implementing the
HttpSessionActivationListener interface are notified.

A servlet should be able to handle cases in which the client does not
choose to join a session, such as when cookies are intentionally turned
off. Until the client joins the session, isNew() returns true. If the client
chooses not to join the session, getSession() will return a different
session on each request, and isNew() will always return true.

Session information is scoped only to the current web application


(ServletContext), so information stored in one context will not be directly
visible in another.

Method Summary
Return Type Description
Object getAttribute(String name)
Returns the object bound with the
specified name in this session, or null if no
object is bound under the name.
Enumeration getAttributeNames()
Returns an Enumeration of String
objects containing the names of all the objects
bound to this session.
long getCreationTime()
Returns the time when this session was
created, measured in milliseconds since
midnight January 1, 1970 GMT.
String getId()
Returns a string containing the unique
identifier assigned to this session.
long getLastAccessedTime()
Returns the last time the client sent a
request associated with this session, as the
number of milliseconds since midnight January
1, 1970 GMT, and marked by the time the

Session Management * Property of STI


Page 3 of 8
F0101

container received the request.


int getMaxInactiveInterval()
Returns the maximum time interval, in
seconds, that the servlet container will keep this
session open between client accesses.
ServletContext getServletContext()
Returns the ServletContext to which this
session belongs.
void invalidate()
Invalidates this session then unbinds any
objects bound to it.
boolean isNew()
Returns true if the client does not yet
know about the session or if the client chooses
not to join the session.
void removeAttribute(String name)
Removes the object bound with the
specified name from this session.
void setAttribute(String name,
Object value)
Binds an object to this session, using the
name specified.
void setMaxInactiveInterval(int interval
)
Specifies the time, in seconds, between
client requests before the servlet container will
invalidate this session.

[Session API, Page 2 of 11]

Retrieving the Session Retrieving the Session Object


Object
Page 3 of 11 The session object is retrieved from the request object that is passed to
Java Enterprise Edition Programming
the servlet by the Web container.
Retrieving the Session
Object public void processSelectLeague(HttpServletRequest
request, HttpServletResponse response) throws
The session object is retrieved from the

request object that is passed to the
IOException
servlet by the Web container.
{
public void
processSelectLeague(HttpServletRequ
est request, HttpServletResponse

{
response) throws IOException //Create the HttpSession object
//Create the HttpSession object
HttpSession session = request.getSession();
HttpSession session =
request.getSession();

The getSession() method returns the current session associated with this
request or if the request does not have a session, the getSession()
method creates one. You can test whether the session object has just
been created using the isNew() method. If the session object already
Session Management * Property of STI
Page 3 of 11 exists, the every call to the getSession() method will return the same
object.

Take note that only one session object will be created for a given client
within a single Web application.

[Retrieving the Session Object, Page 3 of 11]

Session Management * Property of STI


Page 4 of 8
F0101

Storing Session Attributes Storing Session Attributes


Page 4 of 11

Java Enterprise Edition Programming


Once the session object is created, the setAttribute() method can be used
Storing Session to store data in the session scope.
Attributes
//Store the book object in the session
 Once the session object is created, the session.setAttribute(″book″,book);
setAttribute() method can be used to
store data in the session scope.

//Store the book object in the session


session.setAttribute(″book″,book); //select the next view: ″Enter Book″ form
//select the next view: ″Enter Book″
form
response.sendRedirect(″enter_book.html
response.sendRedirect(″enter_book.html″);
″);

The setAttribute() method is used to store information at the session


level. This information will be available to all servlets within the session.
This method binds an object to this session, using the name specified. 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
Session Management * Property of STI
Page 4 of 11 HttpSessionBindingListener, the container calls
HttpSessionBindingListener.valueBound. The container then notifies any
HttpSessionAttributeListeners in the web application. If an object was
already bound to this session of this name that implements
HttpSessionBindingListener, its
HttpSessionBindingListener.valueUnbound() method is called. If the
value passed in is null, this has the same effect as calling
removeAttribute().

The sendRedirect() method 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 URL. 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.

[Storing Session Attributes, Page 4 of 11]

Retrieving Session Attributes Retrieving Session Attributes


Page 5 of 11

Java Enterprise Edition Programming


The getAttribute() method is used to retrieve data in the session object.
Retrieving Session
Attributes //Retrieve domain object from the session

 The getAttribute method is used to Book bk = (Book) session.getAttribute(″book″);


retrieve data in the session object.

//Retrieve domain object from the


session
To retrieve the information stored at the session level, the getAttribute()
Book bk = (Book)
session.getAttribute(″book″); method is used. This method requires you to provide the name of the
object (case sensitive) used when the information is saved at the session
level. It returns the object bound with the specified name in this session,
or null if no object is bound under the name.

[Retrieving Session Attributes, Page 5 of 11]

Session Management * Property of STI


Page 5 of 11

Session Management * Property of STI


Page 5 of 8
F0101

Destroying the Session Destroying the Session


Page 6 of 11

Java Enterprise Edition Programming


There are three methods to destroy a session:
Destroying the Session
When a web application is completed with a session, the servlet can
destroy the session using the invalidate() method.
 There are three methods to destroy a
session:

1. Using the invalidate() method 1. Using the invalidate() method


session.invalidate();

2. Configure a time-out parameter in the


deployment descriptor
<session-config>
session.invalidate();
<session-timeout>10
</session-timeout>
<session-config>

3. Control the length of the inactive interval


There are other two mechanisms for destroying a session; both are
for a specific session object using the
setMaxInactiveInterval() method
managed by the Web container (discussed in items 2 and 3). You can
session.setMaxInactiveInterval(
50); configure a time-out parameter in the deployment descriptor. The value
of the session-timeout element must be a whole number that represents
the number of minutes that a session can exist if the user has left the
Session Management * Property of STI
Page 6 of 11 session inactive. The session-timeout element is located just under the
root web-app element and just after the servlet-mapping elements.

2. Configure a time-out parameter in the deployment descriptor

<session-config>
<session-timeout>10</session-timeout>
<session-config>

The Web container keeps track of the last time the user interacted with
the Web application, which is known as the inactive interval. If a given
session has been inactive for longer than the time-out parameter, then
the Web container has the authority to invalidate that session. The time-
out parameter specified in the deployment descriptor applies to all
sessions within that Web application. The Session API allows you to
control the length of the inactive interval for a specific session object.
You can use the setMaxInactiveInterval() method to change the inactive
interval (in seconds) for the session object.

3. Control the length of the inactive interval for a specific session object
using the setMaxInactiveInterval() method

session.setMaxInactiveInterval(50);

[Destroying the Session, Page 6 of 11]

Session Management * Property of STI


Page 6 of 8
F0101

Session Management Using Session Management Using Cookies


Cookies
Page 7 of 11 Internet Engineering Task Force (IETF) Request for Comment (RFC)
Java Enterprise Edition Programming
#2109 creates an extension to HTTP that allows a Web server to store
Session Management information on the client machine:
Using Cookies
 Cookies are sent in a response from the Web server.
 Cookies are sent in a response from the
Web server.  Cookies are stored on the client’s computer.
 Cookies are stored on the client’s  Cookies are stored in a partition assigned to the Web server’s
computer.
domain name.
 Cookies are stored in a partition assigned
to the Web server’s domain name.

 All Cookies for that domain (and path) are


sent in every request to that Web server.
Cookies can be further partitioned by a “path” within the domain.

 All Cookies for that domain (and path) are sent in every request
to that Web server.

Cookies have a lifespan and are flushed by the client browser at the end
Session Management * Property of STI
Page 7 of 11
of that lifespan.

[Session Management Using Cookies, Page 7 of 11]

Cookie API Cookie API


Page 8 of 11

Java Enterprise Edition Programming


You can create Cookies using the Cookie class in the servlet API. You
can add Cookies to the response object using the addCookie() method.
Cookie API This sends the Cookie information over the HTTP response stream and
the information is stored on the user’s computer, through the Web
Cookies are created using the Cookie class

in the servlet API. The addCookie()
browser. You can access Cookies sent back from the user’s computer in
method is used to add Cookies to the
response object. the HTTP request stream using the getCookies() method. This method
 To access Cookies sent back from the returns an array of all Cookies for the server domain on the client
user’s computer in the HTTP request
stream using the getCookies() method. machine.

Session Management * Property of STI


Page 8 of 11

Page 9 of 11

Java Enterprise Edition Programming

Cookie API

javax.servlet.http

<<interface>>
HttpServlet Cookie
request HttpServletResponse
cookies

service addCookie(Cookie)
<<properties>>
doGet
name : String <<RO>>
doPost
<<interface>> cookies value : String <<RW>>
HttpServletRequest comment : String <<RW>>

response getCookies() : Cookie[]


domain : String <<RW>>
path : String <<RW>>
maxAge : int <<RW>>
Figure 2 – Cookie API
<<constructors>>
Cookie(name, value)

MyServlet [Cookie API, Pages 8-9 of 11]


Figure 2: Cookie API

Session Management * Property of STI


Page 9 of 11

Session Management * Property of STI


Page 7 of 8
F0101

Using Cookies Using Cookies


Page 10 of 11

Java Enterprise Edition Programming


Example:
Using Cookies Imagine that there is a visitor to your Web site and that you want to store
her name so that the next time she visits the site you can personalize the
Example:

screen. In your servlet, you could use the following code to store that
Imagine that there is a visitor to your
Web site and that you want to store her Cookie:
name so that the next time she visits the
site you can personalize the screen. In
your servlet, you could use the following
code to store that Cookie: String name = request.getParameter(″firstName″);
String name = Cookie c = new Cookie(″yourname″,name);
request.getParameter(″firstName″);
Cookie c = new
Cookie(″yourname″,name);
Response.addCookie(c);
Response.addCookie(c);

Later when the visitor returns, your servlet can access the “yourname”
Cookie using the following code:

Session Management * Property of STI


Page 10 of 11
Cookie[] allCookies = request.getCookies();
for(int i=0; i < allCookies.length; i++)
Page 11 of 11
{
if(allCookies[i].getName().equals(″yourname″);
Java Enterprise Edition Programming {
Using Cookies name = allCookies[i].getValue();
}
 Later when the visitor returns, your
}
servlet can access the “yourname” Cookie
using the following code:

Cookie[] allCookies =
HTTP Cookies can be used to perform session management. The Web
request.getCookies();
for(int i=0; i < allCookies.length;
i++)
container could store the session ID on the client machine. While the
{
if(allCookies[i].getName().equals(″y session is still active, every HTTP request from the client includes the
ourname″);
{
name = allCookies[i].getValue();
session ID Cookie that was stored on the client’s machine. When the
}
}
getSession() method is called, the Web container uses the session ID
Cookie information to find the session object.

The Servlet specification mandates that the name of the session ID


Session Management * Property of STI
Cookie be JSESSIONID. The Cookie mechanism is the default
Page 11 of 11

HttpSession strategy. You do not need to code anything in special in


your servlet to make use of this session strategy. Unfortunately, some
browsers do not support Cookies or some users turn off Cookies in their
browsers. If that happens, then the Cookie-based session management
fails.

[Using Cookies, Pages 10-11 of 11]

EVALUATION:

o Ask the students to perform the laboratory exercise for this topic.

REFERENCES:

o Cadenhead, Rogers and Lemay, Laura, Sams teach yourself


java™ 2 in 21 days (4th ed.)
o van der LINDEN, Peter, Just Java™ 2 (6th ed.)
o The Java Tutorial - An excellent collection of on-line from SUN
Microsystems (http://java.sun.com/docs/books/tutorial/)
o Schildt, Herbert, Java 2 the complete reference (5th ed.)

Session Management * Property of STI


Page 8 of 8

You might also like