Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes Chapter 6(Session Management)  notes (HFSJ) for revision Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "Chapter 6(Session Management)  notes (HFSJ) for revision" Watch "Chapter 6(Session Management)  notes (HFSJ) for revision" New topic

Chapter 6(Session Management) notes (HFSJ) for revision

Vishal Chugh
Ranch Hand

Joined: Oct 27, 2007
Posts: 177
1) Web-servers don’t remember a client , as soon as they send the response they forget about the client i.e which client they served , what was requested by that client , what they sent in response , when this client again sends the request , they don’t recognize him that it is the same client to whom they served few seconds back.
2) But sometimes we want the web-server to “remember the client” and recognize it when it sends the request again , and also to remember “what this client requested “ in past and what they served in the response in past :

Eg : 1) Shopping cart example requires the web-server to remember what the client requested when it came last time i.e which items he/she had put in his cart.

2) If servlet is designed to send the response (some suggestion) based on the request parameter sent , if the client request first time its okay to send any suggestion but if the client request comes next time , servlet wanna make sure that it doesn’t send the same response (same suggestion) again.

3) In technical terms : we want to keep the conversation state of the client b/w the multiple requests.

4) To achieve this , we will store the (the things which we want the session to remember) objects(attributes) in the session object and will retrieve the objects from session object.

5) We have API to work with sessions .

6)About HttpSessionListner , HttpSessionAttributeListner , HttpSessionActivationListner & HttpSessionBindingListener -- API .

7)Cookies , URL-rewriting --- to manage the sessions

8) How we can keep track of client answers ? (Options available)
a) Using stateful session beans --- maintaining the stateful session beans and finding the corresponding session bean when the client comes again.
b) Using DB --- to store the client requests.
c) Using the HttpSession objects to store the client specific info .

9) An HttpSession object persists across multiple requests from the same client. We can use to store everything we get back from the client , in all the requests the client makes during the session.

10) I saw the two below scenarios :
a) Same client
b) Same servlet requested again
c) Different request sent.
d) Different threads got created.
e) Same session was maintained.

2) a) Different clients
b) Different requests
d) Same servlet
e) Different threads
f) Different sessions

11) HTTP protocol uses the stateless connections : Client browser makes the connection to server , makes the request to server , gets the response and closes the connection --- “ Connection exists for single client request/response .” Because the connections don’t persist , container doesn’t recognize the client making the second request is the same client from previous request.

12) JFYI --- To server the client IP address is the IP address of the router .

13) To work with sessions :

a) Each client is given the unique session ID : When the client request for the first time , it is given the unique ID
b) Then client sends back the session ID with each subsequent requests .
c) The container sees the ID , finds the matching session and associates the session with the current request .

14) But there is big but , :”how” the container will send the session ID in response to the client when it receives the client request first time AND how the client will send the session ID info back : Using cookies.

a) Container sets the response header named : Set-Cookie with the value JSESSIONID=1234567890POLD
b) Then the client responds with setting the Cookie header in the next request sent to container with value JSESSIONID=1234567890POLD

15) If we want to use/create the session for the clients , we will just do below :
HttpSession s = request.getSession() ; in our doGet() or doPost() method

It will do the following :
1) Whenever any client request comes , it (container) will look for session ID sent in request to find the session object related with this client , if found then it will use that , otherwise it will create session for this client . If this is a client requesting first time then new session object must be created for it
2) Then it assigns the session ID to session object created for the new client , if it was newly created session.
3) Then it will create the new Cookie object
4) and then associate the session ID with that cookie .
5) Then set the cookie in the response object .

16) For both setting a session cookie in response and for getting the session id from request , we use below :
HttpSession s = request.getSession() ;

This method is magic method , it will first check for session ID cookie if it existed , if existed then fine , otherwise a new session object will be created , then if we want to know whether it is a already existing session or new one , we can use below :

If (s.isNew())

what if I don’t wanna create a new session , just wanna existing session if there otherwise null if not there, we use below :

HttpSession s = request.getSession(false) ;

17) Very IMP : we can get the session from below objects :
1) request object as above
2) HttpSessionEvent object ( event object)
3) HttpSessonBindingEvent object.( even object subclass of (b))
We use getSession() method with all three for sessions.

e.g : public void sessionCreated(HttpSessionEvent e)
HttpSession s = e.getSession();

18) Below are same :

HttpSession s = request.getSession() ; and
HttpSession s = request.getSession(true) ;

19) But what if the client browser has disabled the cookies , what if we still want to use the sessions : there is a way for it : To use the URL rewriting , we have to encode our URL’s in our dynamic HTML response , what we will do is we will attach the Session Id info at the end of URL hyperlinks and so that when client will click those links , request will come to server with session ID attached to them and it will recognize the client from the session id attached , but we have to encode our all URLs manually L .. It can be done as below .

response.encodeURL(“/”); in out.println(“<a href= \ “” + response.encodeURL(“/”) + “\” >click me </a>”);

Once again , URL rewriting takes the session ID , that’s in the cookie and sticks it right to every URL that comes in to this application.


20) I have read , the container will try to use both initially cookies as well as URL rewriting (provided URLs have been encoded) , if cookie doesn’t come back in response,
it will go with URL rewriting .

21) For scenarios , where we want to redirect the request to different URL but want to have URL rewriting also , we will use the below :


22) Very Imp : we can do URL rewriting in dynamic response only , not in static HTMLs , Please note JSPs are also dynamic response , they can have this method , but there we cant have java , we have substitute for it : <c:URL> tag

23) URL rewriting is a performance hit, be careful about its usage.

24)From book “ URL rewriting is automatic provided you have encoded your URLs using either of the two methods”

25) Remember , URL rewriting is handled in a vendor specific way.

26) We expect to see always :
a) JSESSIONID=123456tyyuuuu as an header value for Cookie header in request
b) and jsessionid attached to URLs end in requests sent to container

27) If we want to use the sessions we have to generate response dynamically ( Dynamic HTMLs) as with static HTMLs URL rewriting wont work .

28) To manage and handle the sessions on the server side , javax.servet.http.HttpSession API has gifted us many useful methods as below :( 3 getters , one setter and invaildate )

a) setMaxInactiveInterval(TIME IN SECONDS);
b) getMaxInactiveInterval();
c) getCreationTime();
d) getLastAccessedTime();
e) invalidate();

29) We can configure the session timeout(IN MINUTES) in DD if in case we want to have same session timeout interval for all sessions created in a web-app as below: (otherwise call up the s.setMaxInactiveInterval(“Time in seconds”) on a particular session object s for which you want to have different timeout interval ) :

<session-timeout>15 </session-timeout>

30) So our session can be destined to death in below three ways:
1) If session-timeout occurs.
2) Invalidate method invoked on session object
3) And application crashed.

31) Once the session is invalidated by calling the invalidate() method on session object, you can’t access any session attribute now , if you try you will get IllegalStateException (which is runtime exception) .

32)s.setMaxInactiveInterval(0); will invalidate the session immediately

33)Cookie --- Piece of info exchanged b/w client and server , though cookies are used for session management but we can use cookies for our some purpose also .To that kind of cookie , we call custom cookie.

34) ”Session cookies” vanish when the client’s browser quits , but you can tell a cookie to persist on the client even after the browser shuts down. Such cookies will be custom cookies.
e.g : Conatiner can set the user-name cookie when the client request for the first time and when it gets the request back , it can ask for cookie user-name to display welcome message like “Hello username”.

In response it would be set like :
Set-Cookie : user-name=12345678790hhhdfghklp

In request it will come like :
Cookie:user-name: 12345678790hhhdfghklp

35)API has cookie related methods ;
a) javax.servlet.http.HttpServletRequest has getCookies() ----- Please note it returns an array of cookie objects , then we have to call getName() and getValue() on each cookie object to check the name and value of cookie .

b) javax.servlet.http.HttpServletResponse --- addCookie() --- to add custom cookie object to response
c) javax.servlet.http.Cookie has below methods :
a) Cookie(String, String) ---- first String is name of cookie , second String is value of cookie
b) String getName()
c) String getValue()
d) void setMaxAge(int)
e) int getMaxAge()
f) void setPath(String)
g) String getPath()
h) void setDomain(String)
i) String getDomain()

36)Creating the custom cookie and getting it back and working on it:

Cookie c = new Cookie(“username” , name);
response.addCookie( c );

Getting cookie back :
Cookie[] ck = response.getCookies();
for(int i=0 ; i<ck.length ; i++)
Cookie c = ck[ i];
{ String value = c.getValue();
out.println(“Hello” + value);

37) Very Imp ---- HttpSessionAttributeListner uses event HttpSessionBindingEvent
HttpSessionActivationListner uses event HttpSessionEvent

38) Simple : HttpSessionListner uses HttpSessionEvent .

39)HttpSessionBindingListener example :

package com.example;
import javax.servlet.http.*;

public class Dog implements HttpSessionBindingListener{

private String breed;
public Dog(String b)
breed = b;
String getBreed()
return breed;

public void valueBound(HttpSessionBindingEvent e)
{ }
public void valueUnBound(HttpSessionBindingEvent e)
{ }

30) HttpSessionBindingListner --- Not configured in DD
HttpSessionListner,HttpSessionAttributeListner, HttpSessionActivationListner --- Configured in DD.

31)In distributed web-app , same client request could end up in different servlet instance(of same servlet A) on different JVM: (due to load balancing)
Client X --- request A ---- Servlet A --- VM 1
Client X ---- request B ---- Servlet A ---- VM 2

Point of focus : while routing the request from VM1 to VM2 (“Duplication" [to copy] occurs OR "Migration” [to move] occurs ) in distributed web-app are :
1) HttpSession object --- migrated
2) ServletContext object --- duplicated
3) ServletConfig object --- duplicated .

“When session will be migrated to different VM , its session ID will not change.”
No two sessions in two VMs will have the same session ID.

32) Don’t forget from book "the Session Migration need and way it is done" , the full scenario dia.

33)While session migration , attribute objects (which have instance variables) [which have been set in that session which is migrating using setAttribute method ] are also a big concern:
a) If all attributes classes are serializable/null , then no need to worry , they will survive the migration .
b) If attribute classes don’t implement Serializable , they wont survive the migration [b]until and unless they don’t implement the HttpSessionActivationListner [/b]

BottomLine : HttpSessionActivationListner takes the responsibility of making the attributes ready for migration and getting them back for access after the migration.

34) HttpSessionListner example : To count the number of active sessions in this web-app

package com.example;
import javax.servlet.http.*;
public class SC implements HttpSessionListener {

static private int activesessions;

public void sessionCreated(HttpSessionEvent e)


public void sessionDistroyed(HttpSessionEvent e)



Configuring in DD :


35) HttpSessionAttributeListner example : To keep the track of attributes added/removed/replaced into the session , “we will check(print) the attribute name and its value every time the attributes are added/removed/replaced.”

package com.example;
import javax.servlet.http.*;

public class AL implements HttpSessionAtributeListener {

public void attributeAdded(HttpSessionBindingEvent e)
String name = e.getName();
Object value = e.getValue();
S.o.p(“Attribute added”+ name + “value” + object);

public void attributeRemoved(HttpSessionBindingEvent e)
String name = e.getName();
Object value = e.getValue();
S.o.p(“Attribute removed”+ name + “value” + object); // check tomcat/logs/Catalina.log


public void attributeReplaced(HttpSessionBindingEvent e)
String name = e.getName();
Object value = e.getValue();
S.o.p(“Attribute replaced”+ name + “value” + object); // check tomcat/logs/Catalina.log


Configuring in DD :


36) Remember HttpSessionActivationListner “is also for attribute classes to implement” like they implement HttpSessionBindingListener --- Very ImP.

37)HttpSessionBindingListner and HttpSessionActivationListner combined example:

package com.example;
import javax.servlet.http.*;

public class SBSAL implements HttpSessionBindingListner , HttpSessionActivationListner , Serializable{

private String breed;

public void valueBound(HttpSessionBindingEvent e)
public void valueUnbound(HttpSessionBindingEvent e)

public void sessionDidActivate(HttpSessionEvent e)

public void sessionWillPassivate(HttpSessionEvent e)


Configuring in DD :


[ I have tried best to keep it a good document , but mistakes caught by you all , are welcome :) ]
Salim Khatib

Joined: Jan 06, 2009
Posts: 23
<!-- 30) HttpSessionBindingListner --- Not configured in DD
HttpSessionListner,HttpSessionAttributeListner, HttpSessionActivationListner --- Configured in DD -->

Can you please verify thus point , I think it should be

HttpSessionListner --- Not Configured in DD
HttpSessionBindingListner,HttpSessionAttributeListner, HttpSessionActivationListner --- Configured in DD -->

SCJP 1.4 - 75%
SCWCD 1.5 - 97%
SQL Oracle 9i - 94%
IBM AIX - 93%
Christophe Verré

Joined: Nov 24, 2005
Posts: 14687

Check this FAQ.

[My Blog]
All roads lead to JavaRanch
Salim Khatib

Joined: Jan 06, 2009
Posts: 23
You mean the correct answer is

HttpSessionListener and HttpSessionAttributeListener should be configured in DD
HttpSessionBindingListener, HttpSessionActivationListener are not configurable in DD

m I right ?
Christophe Verré

Joined: Nov 24, 2005
Posts: 14687


By the way, can you check the ranch's Naming Policy and fix your name accordingly ? Thank you.
Salim Khatib

Joined: Jan 06, 2009
Posts: 23
I agree. Here's the link:
subject: Chapter 6(Session Management) notes (HFSJ) for revision
Similar Threads
Session and cookies
session time out issue it is not get expired in any way
How to get HttpSessionListener to respond?
Confusion about session destruction
URL rewriting is not working