What is a session? What is the difference between session and cookie?

Bozidar Dangubic

[See the topic Servlets: Sessions and the question How do I use Session Tracking? -Alex]

A session is an object associated with a client connection to the server. it has the ability to carry information related to the client. since http is a connectionless protocol, developers need an ability to "remember" what the client of the application did during the visit to the page. a great example of the need and use of session is a infamous shopping cart. as users browse through products they are interested in, they add products they want to buy to the 'shopping cart' this information needs to be stored somewhere so that when users decides to check-out and purchase the products, the system knows all the products client wants to purchase. so 'shopping cart' is stored in the session which drags along on each client invocation to the server until session expires.

the way server handles session is server-specific. the specification does not specify exact implementation of the session. some web servers may use cookies, some may use something else. but overall, it is up to the implementer to decide how this is done.

the difference between session and a cookie is two-fold.
1) session should work regardless of the settings on the client browser. even if users decide to forbid the cookie (through browser settings) session still works. there is no way to disable sessions from the client browser.
2) session and cookies differ in type and amount of information they are capable of storing. javax.servlet.http.Cookie class has a setValue() method that accepts Strings. javax.servlet.http.HttpSession has a setAttribute() method which takes a String to denote the name and java.lang.Object which means that HttpSession is capable of storing any java object. Cookie can only store String objects.
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact