Monday, February 4, 2013

Head First Servlets and JSP: Chapter 6 Sessions & Cookies

1- The container takes care of sessions
2- HttpSession s = request.getSession();
is used to get a session or to create a new session.
3- you can check if (session.isNew()) to check if the session is new
4- you can use request.getSession(false) to return a session only if it was created before otherwise it returns null.
5- the container adds jsessionid to cookie.
6- if a user doesnt enable cookies, then you can add jsessionid to the query string, you can do that by using
response.encodeUrl("THE URL");
the encodeUrl() will add the session information

7- never do something like
String sessionId = request.getParameter("jsessionid"); 

always read the session form request.getSession();

Session Interface
the session interface has important methods like:
setMaxInteractiveInterval(): this is to set timeout for a specific session

Session timeout
to set session timeout you can add the following to web.xml

some functions that you may use them when it comes to cookies

1- Cookie x = new Cookie("userName","hassan")
2- x.setMaxAge(30*60)
3- response.addCookie(x);
4- request.getCookies()

Distributed Systems Cluster and ServletContext, ServletConfig and Session
when we have a multiple machine in cluster, each machine will have a ServletContext and ServletConfig, however the session information are shared among all machines.
The session will be migrated from machine to another

Session Listeners
there are number of listeners that can be used with sessions
1- HttpSessionListners: will listen to when the session is created or destroyed
2- HttpSessionActivationListener: this is used when session is moved from one machine to another in a cluster, sessionDidActivate and sessionWillPassivate
3- HttpSessionBindingListener: this one you add it to a class, so it will be notified when a class object is added to a session or removed

public class Car implements HttpSessionBindingListener {
   public void valueBound()
   public void valueUnBound()

4- HttpSessionAttributeListener: will listen to when a new attribute is added or removed from a session, attributeAdded and attributeRemoved and attributeReplaced

No comments:

Post a Comment