Session Tracking:
HTTP is a stateless protocol. Each request is independent of the previous one. However, in some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide such a mechanism.
- Http Session
- Cookies
1. Http Session:
- It is used for saving client details at server-side.
- Session object can be created by calling the getSession( ); method.
- For retreiving the values from the session object, we can use the getAttribute( );
HttpSession hs = req.getSession( );
hs.setAttribute(“sname”,name);
String s = (String) hs.getAttribute(sname);
- It creates the new session id for each client and the session object is available until the session time expires.
2. Cookies:
- It is used to save the client details at the client-side itself.
- It is also used for client validations.
- The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state information. Cookies are valuable for tracking user activities.
- For example, assume that a user visits an online store. A cookie can save the user’s name, address, and other information. The user does not need to enter this data each time he or she visits the store.
- A servlet can write a cookie to a user’s machine via the addCookie( ) method of the HttpServletResponse The data for that cookie is then included in the header of the HTTP response that is sent to the browser.
- Cookie is a class, by creating cookie object, it allows to store the client details:
Cookie c1 = new Cookie(“sname”, name);
Cookie c2 = new Cookie(“address”, hyd);
res.addCookie(c1);
res.addCookie(c2);
- To retreive values from the cookie object:
Cookie[ ] = req.getCookies( );
pw.println(c[0].getName( ));
pw.println(c[0].getValue( ));