Sunday, 13 November 2011

HTTP Sessions-From book java/j2ee interview

A session identifies the requests that originate from the same browser during the period of conversation. All the servlets can share the same session. The JSESSIONID is generated by the server and can be passed to client through cookies, URL re-writing (if cookies are turned off) or built-in SSL mechanism. Care should be taken to minimize size of objects stored in session and objects stored in session should be serializable.

Session tracking uses cookies by default. What would you do if the cookies are turned off?
If cookies are turned off, you can still enable session tracking using URL rewriting. This involves including the session ID within the link as the name/value pair as shown below.

Adding session ID to each and every link is cumbersome and hence is simplified by the following methods: response.encodeURL(givenURL) to associate a session ID with a given URL and if you are using redirection then response.encodeRedirectURL(givenURL).
public class CRMServlet extends HttpServlet {
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     req.getSession().setAttribute("key", "ItemNo-1245");
     String url = resp.encodeURL("/myWebCtxt/");
     PrintWriter pw = resp.getWriter();
     pw.println("Sample encoded URL -->purchase");
When you invoke the method encodeURL(givenURL) with the cookies turned on, then session ID is not appended to the URL. Now turn the cookies off and restart the browser. If you invoke the encodeURL(givenURL) with the cookies turned off, the session ID is automatically added to the URL as follows:

No comments:

Post a Comment