Академический Документы
Профессиональный Документы
Культура Документы
Lecture 32
Session Tracking 2
In the last handout we have discussed the solutions for session tracking and talked about
one important mechanism cookies in detail. We said cookies allow the server to store
information on a client machine and later retrieve it. Now we will see two more
mechanisms that provide us facility to maintain a session between user’s requests. These
are URL Rewriting and Hidden Form Fields. After that we will discuss a session tracking
API provided by java.
URL Rewriting
URL rewriting provides another way for session tracking. With URL rewriting, the
parameter that we want to pass back and forth between the server and client is appended
to the URL. This appended information can be retrieve by parsing the URL. This
information can be in the form of:
Note: Due to limited space available in rewriting a URL, the extra information is usually
limited to a unique session ID.
The following URLs have been rewritten to pass the session ID 123
What if the user bookmarks the page and the problem get worse if server is not
assigning a unique session id.
Every URL on a page, which needs the session information, must be rewritten
each time page is served, which can cause
- Computationally expensive
- Can increase communication overhead
-392 -
Handout 32
Web Design & Development CS-506
This mechanism limits the client interaction with the server to HTTP GET
request.
This is the modified version of online book store (selling two books only, however you
can add in on your own) that is built using cookies in the last handout. Another important
difference is books are displayed in the form of hyperlink instead of check boxes. URL
rewriting mechanism is used to maintain session information.
Now, if you want to pass some attribute and values along with URL, you can use the
technique of query string. Attribute names and values are written in pair form after the ?.
For example, if you want to send attribute “name” and its value “ali”, the URL will look
like
Original URL
http://server:port/servletex /register
If you want to add more than one parameter, all subsequent parameters are separated by
& sign. For example
- 393 -
Handout 32
Web Design & Development CS-506
URLRewriteServlet.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
// reading sessionId
String sID = request.getParameter(“JSESSIONID”);
if (sID == null)
{
// make a unique string
sID = makeUniqueString();
- 394 -
Handout 32
Web Design & Development CS-506
}else {
sessionInfo = (HashMap)globalMap.get(sID);
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Shopping Cart Example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Online Book Store</h1>");
String firsturl =
"http://localhost:8084/urlbookstore/urlrewriteservlet?JSESSIONID="
+ sID + "&firstCB=firstCB";
String secondurl =
"http://localhost:8084/urlbookstore/urlrewriteservlet?JSESSIONID="
+ sID + "&secondCB=secondCB";
);
out.println("<br/>");
out.println("<h1>You have selected following books</h1>");
out.println("<br/>");
- 395 -
Handout 32
Web Design & Development CS-506
out.println("</body>");
out.println("</html>");
out.close();
} // end processRequest()
title= (String)sessionInfo.get("firstCB");
if (title != null){
out.println("<h3> "+ title +"</h3>");
}
title= (String)sessionInfo.get("secondCB");
if (title != null){
out.println("<h3> "+ title +"</h3>");
}
}
} // end URLRewriteServlet
- 396 -
Handout 32
Web Design & Development CS-506
web.xml
<web-app>
<servlet>
<servlet-name> URLRewriteServlet </servlet-name>
<servlet-class> URLRewriteServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> URLRewriteServlet </servlet-name>
<url-pattern> /urlrewriteservlet </url-pattern>
</servlet-mapping>
</web-app>
-------------------
- 397 -
Handout 32
Web Design & Development CS-506
Hidden Forms Fields do not affect the appearance of HTML page. They actually contain
the information that is needed to send to the server. Thus, hidden fields can also be used
to store information (like sessionid) in order to maintain session.
In the above figure you can see the use of Hidden form fields for storing particular
information.
- 398 -
Handout 32
Web Design & Development CS-506
If true is passed to the getSession() method, this method returns the current
session associated with this request, or, if the request does not have a session, it
creates a new one. We can confirm whether this session object (sess) is newly
created or returned by using isNew() method of HttpSession. In case of passing
false, null is returned if the session doesn’t exist.
- 399 -
Handout 32
Web Design & Development CS-506
String sid=(String)sess.getAttribute(“sessionid”);
4. Terminating a Session
After the amount of time, session gets terminated automatically. We can see its
maximum activation time by using getMaxInactiveInterval() method of
HttpSession class. However, we can also terminate any existing session
manually. For this, we need to call invalidate() method of HttpSession
class as shown below.
sess.invalidate()
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
- 400 -
Handout 32
Web Design & Development CS-506
{
processRequest(request, response);
}
response.setContentType("text/html");
if (accessCount == null)
{
accessCount = new Integer(1);
heading = "Welcome, Newcomer";
} else
{
heading = "Welcome Back";
session.setAttribute("sessionCount", accessCount);
// Getting the PrintWriter
-401 -
Handout 32
Web Design & Development CS-506
" </BODY>" +
" </HTML>"
);
} // end processRequest
web.xml
<web-app>
<servlet>
<servlet-name> ShowSession </servlet-name>
<servlet-class> ShowSessionServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> ShowSession </servlet-name>
<url-pattern> /showsession </url-pattern>
</servlet-mapping>
</web-app>
-----------------
HttpSession – Behind the scenes
When we call getSession() method, there is a lot going on behind the scenes. For
every user, a unique session ID is assigned automatically. As the server deals with lot of
users at a time, this ID is used to distinguish one user from another. Now here is the
question, how this ID sends to the user? Answer is, there are two options
Option 1: If the browser supports cookies, the Servlet will automatically creates a
session cookie and store the session ID within that cookie.
Option 2: If the first option fails because of browser that does not support cookies
then the Servlet will try to extract the session ID from the URL
- 402 -
Handout 32
Web Design & Development CS-506
If Cookies are disabled, both methods encode (rewrite) the specific URL to include the
session ID and returns the new URL. However, if cookies are enabled, the URL is
returned unchanged.
encodeURL() is used for URLs that are embedded in the webpage, that the servlet
generates. For example,
- 403 -
Handout 32
Web Design & Development CS-506
This book store is modified version of last one, which is built using URL rewriting
mechanism. Here, HttpSession will be used to maintain session.
ShoppingCartServlet.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html;charset=UTF-8");
out.println("<html>");
out.println("<head>");
out.println("<title>Shopping Cart Example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Online Book Store</h1>");
- 404 -
Handout 32
Web Design & Development CS-506
// Encoding URLs
String eURL1 = response.encodeURL( firstURL );
String eURL2 = response.encodeURL( secondURL );
out.println(
"<h3><a href=" + eURL1 + ">" +
" java core servlets </a> </h3>" +
"<br>"+
out.println("<br/>");
out.println("<h1>You have selected following books</h1>");
out.println("<br/>");
out.println("<br/>");
out.println("<h1>You have selected following books</h1>");
out.println("<br/>");
if (book != null){
}//outer if ends
- 405 -
Handout 32
Web Design & Development CS-506
out.println("</body>");
out.println("</html>");
out.close();
} // end processRequest()
if (title != null){
out.println("<h3> "+ title +"</h3>");
}
if (title != null){
out.println("<h3> "+ title +"</h3>");
}
} // end printSessionInfo
} // end ShoppingCartServlet
web.xml
<web-app>
<servlet>
<servlet-name> ShoppingCartServlet </servlet-name>
<servlet-class> ShoppingCartServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> ShoppingCartServlet </servlet-name>
<url-pattern> /shoppingcart </url-pattern>
</servlet-mapping>
</web-app>
- 406 -
Handout 32
Web Design & Development CS-506
setAttribute(String, Object)
This method associates a value with a name.
getAttribute(String)
Extracts previously stored value from a session object. It returns null if no value
is associated with the given name
removeAttribute(String)
This method removes values associated with the name
getId( )
This method returns the unique identifier of this session
getCreationTime( )
This method returns time at which session was first created
getMaxInactiveInterval( ) , setMaxInactiveInterval(int)
To get or set the amount of time session should go without access before being
invalidated.
--------------------
- 407 -
Handout 32
Web Design & Development CS-506
References:
- 408 -