Managing Session using URL Rewriting

We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, we can still enable session tracking using URL rewriting.

URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, we need to append the session ID for each and every link that is part of our Servlet response.

Adding the session ID to a link is greatly simplified by means of a couple of methods: 

   a) response.encodeURL() associates a session ID with a given URL, and

   b) if 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.

The example codes are placed within UrlRewrite  directory under webapps.

 

See the program below:

UrlRewrite.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class UrlRewrite extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter pw = response.getWriter();
HttpSession session = request.getSession();
pw.println("");
pw.println("response.encodeURL("/UrlRewrite/test.do") + "\">Click On Me");
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

 

The web.xml file for this web application:

<web-app>
<servlet>
<servlet-name>amt</servlet-name>
<servlet-class>TestingServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>amt1</servlet-name>
<servlet-class>UrlRewrite</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>amt</servlet-name>
<url-pattern>/test.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>amt1</servlet-name>
<url-pattern>/rewrite.do</url-pattern>
</servlet-mapping>
</web-app>

 

In the above DD, TestingServlet is the First Servlet written in the Advanced Java Tutorial.

The output of the program is given below: 

 

 

 

 

 

 

 

 

On clicking the link “Click On Me” will produce the following output:

 

 

See the following URL in the address bar of the web browser:  

http://localhost:8085/UrlRewrite/test.do;jsessionid=BDA3003D028F56EED5D7235DAB69B16C 

Certainly, the part of the above URL (marked in bold font) starting with “jsessionid” shows the effect of encoding the URL.