ITP

MCA - Advanced Java Programming

How can I enable session tracking for JSP pages if the browser has disabled cookies ?

In : MCA Subject : Advanced Java Programming

Cookies are used by default in session tracking to associate a session identifier with a unique user. If your browser does not support cookies or if cookies are disabled, you can still use URL rewriting to enable session tracking. The session ID is effectively included as a name/value pair within the URL rewriting. However, in order for this to work, you must attach the session ID to each and every link in your servlet response.

Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input.

Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie.

Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object.

hello1.jsp
-----------
<%@ page session="true" %>
<%
  Integer num = new Integer(100);
  session.putValue("num",num);
 String url =response.encodeURL("hello2.jsp");
%>
<a href='<%=url%>'>hello2.jsp</a>

hello2.jsp
-------------
<%@ page session="true" %>
<%
  Integer i= (Integer )session.getValue("num");
  out.println("Num value in session is "+i.intValue());
%>

About us

A truly open platform where you may ask questions and get answers. We also provide comprehensive and easy-to-understand answers to question papers.  discover...

Site status

Flag Counter

Privacy Policy

Sitemap