From Twitter

A Hit Count Using Session Tracking

A Hit Count Using Session Tracking

 Let us understand session tracking with a simple servlet to count the number of times
a client has accessed it, as shown in example below. The servlet also displays all the
bindings for the current session, just because it can.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionTracker extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// Get the current session object, create one if necessary
HttpSession session = req.getSession(true);
// Increment the hit count for this page. The value is saved
// in this client's session under the name "tracker.count".
Integer count = (Integer)session.getValue("tracker.count");
if (count == null)
count = new Integer(1);
else
count = new Integer(count.intValue() + 1);
session.putValue("tracker.count", count);
out.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>");
out.println("<BODY><H1>Session Tracking Demo</H1>");
// Display the hit count for this page
out.println("You've visited this page " + count +((count.intValue() == 1) ? " time." : "
times."));
out.println("<P>");
out.println("<H2>Here is your session data:</H2>");
String[] names = session.getValueNames();
for (int i = 0; i < names.length; i++) {
out.println(names[i] + ": " + session.getValue(names[i]) + "<BR>");
}
out.println("</BODY></HTML>");
}}

 The output will appear as:
Session Tracking Demo
You’ve visited this page 12 times
Here is your session Data
movie.level : beginner
movie.zip : 50677
tracker.count : 12
This servlet first gets the HttpSession object associated with the current client. By
passing true to getSession(), it asks for a session to be created if necessary. The servlet
then gets the Integer object bound to the name “tracker.count”. If there is no such
object, the servlet starts a new count. Otherwise, it replaces the Integer with a new
Integer whose value has been incremented by one. Finally, the servlet displays the
current count and all the current name/value pairs in the session.
Session Tracking using persistent Cookies
 
Another technique to perform session tracking involves persistent cookies. A cookie
is a bit of information sent by a web server to a browser is stored it on a client
machine that can later be read back from that browser. Persistent cookies offer an
elegant, efficient, easy way to implement session tracking. Cookies provide as
automatic introduction for each request as you could hope for. For each request, a
cookie can automatically provide a client’s session ID or perhaps a list of the client’s
preferences. In addition, the ability to customize cookies gives them extra power and

versatility. When a browser receives a cookie, it saves the cookie and thereafter sends Servlet Programming
the cookie back to the server each time it accesses a page on that server, subject to
certain rules. Because a cookie’s value can uniquely identify a client, cookies are
often used for session tracking.
Note: Cookies were first introduced in Netscape Navigator. Although they were not
part of the official HTTP specification, cookies quickly became a de facto
standard supported in all the popular browsers including Netscape 0.94 Beta
and up and Microsoft Internet Explorer 2 and up.


Problem: The biggest problem with cookies is that all the browsers don’t always
accept cookies. Sometimes this is because the browser doesn’t support cookies.
Version 2.0 of the Servlet API provides the javax.servlet.http.Cookie class for
working with cookies. The HTTP header details for the cookies are handled by the
Servlet API. You create a cookie with the Cookie() constructor:
public Cookie(String name, String value)
 
This creates a new cookie with an initial name and value..
A servlet can send a cookie to the client by passing a Cookie object to the
addCookie() method of HttpServletResponse:
public void HttpServletResponse.addCookie(Cookie cookie)
 
This method adds the specified cookie to the response. Additional cookies can be
added with subsequent calls to addCookie(). Because cookies are sent using HTTP
headers, they should be added to the response before you send any content. Browsers
are only required to accept 20 cookies per site, 300 total per user, and they can limit
each cookie’s size to 4096 bytes.
The code to set a cookie looks like this:
Cookie cookie = new Cookie(“ID”, “123”);
res.addCookie(cookie);
 
A servlet retrieves cookies by calling the getCookies() method of HttpServlet-
Request:
public Cookie[] HttpServletRequest.getCookies()
This method returns an array of Cookie objects that contains all the cookies sent by
the browser as part of the request or null if no cookies were sent. The code to fetch
cookies looks like this:
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {

String name = cookies[i].getName();
String value = cookies[i].getValue();
}
}
You can set a number of attributes for a cookie in addition to its name and value. The
following methods are used to set these attributes. As you will see, there is a
corresponding get method for each set method. The get methods are rarely used,
however, because when a cookie is sent to the server, it contains only its name, value,
and version.
 

Here some of the methods of cookies are listed below which are used for session
tracking:
public void Cookie.setMaxAge(int expiry)
Specifies the maximum age of the cookie in seconds before it expires. A negative
value indicates the default, that the cookie should expire when the browser exits. A
zero value tells the browser to delete the cookie immediately

 public int getMaxAge();
 
This method returns the maximum specified age of the cookie. If no maximum age
was specified, this method returns -1.
 
  public void Cookie.setVersion(int v)
 
Sets the version of a cookie. Servlets can send and receive cookies formatted to match either Netscape persistent cookies (Version 0) or the newer
 
public String getDomain();
 
Returns the domain of this cookie, or null if not defined.
 
public void Cookie.setDomain(String pattern)
 
This method sets the domain attribute of the cookie. This attribute defines which hosts
the cookie should be presented to by the client. A domain begins with a dot (.foo.com)
and means that hosts in that DNS zone (www.foo.com but not a.b.foo.com) should see
the cookie. By default, cookies are only returned to the host which saved them.
 
public void Cookie.setPath(String uri)
 
It indicates to the user agent that this cookie should only be sent via secure channels
(such as HTTPS). This should only be set when the cookie’s originating server used
a secure protocol to set the cookie’s value.
public void Cookie.setValue(String newValue) Assigns a new value to a cookie.
 
public String getValue()

This method returns the value of the cookie.
Let us understand how we use persistent cookies for the session tracking with the help
of shopping cart example

// Session tracking using persistent cookies
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShoppingCartViewerCookie extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// Get the current session ID by searching the received cookies.
String sessionid = null;
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("sessionid")) {
sessionid = cookies[i].getValue();
break;
}
}
}

// Session tracking using persistent cookies
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShoppingCartViewerCookie extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// Get the current session ID by searching the received cookies.
String sessionid = null;
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("sessionid")) {
sessionid = cookies[i].getValue();
break;
}
}
}// If the session ID wasn't sent, generate one. Servlet Programming
// Then be sure to send it to the client with the response.
if (sessionid == null) {
sessionid = generateSessionId();
Cookie c = new Cookie("sessionid", sessionid);
res.addCookie(c);
}
out.println("<HEAD><TITLE>Current Shopping Cart
Items</TITLE></HEAD>");
out.println("<BODY>");
// Cart items are associated with the session ID
String[] items = getItemsFromCart(sessionid);
// Print the current cart items.
out.println("You currently have the following items in your cart:<BR>");
if (items == null) {
out.println("<B>None</B>");
}
else {
out.println("<UL>");
for (int i = 0; i < items.length; i++) {
out.println("<LI>" + items[i]);
}
out.println("</UL>");
}

 // Ask if they want to add more items or check out.
out.println("<FORM ACTION=\"/servlet/ShoppingCart\" METHOD=POST>");
out.println("Would you like to<BR>");
out.println("<INPUT TYPE=submit VALUE=\" Add More Products/Items \">");
out.println("<INPUT TYPE=submit VALUE=\" Check Out \">");
out.println("</FORM>");
// Offer a help page.
out.println("For help, click <A HREF=\"/servlet/Help" +
"?topic=ShoppingCartViewerCookie\">here</A>");
out.println("</BODY></HTML>");
}
private static String generateSessionId() {
String uid = new java.rmi.server.UID().toString(); // guaranteed unique
return java.net.URLEncoder.encode(uid); // encode any special chars
}
private static String[] getItemsFromCart(String sessionid) {
// Not implemented
}
}
This servlet first tries to fetch the client’s session ID by iterating through the cookies it
received as part of the request. If no cookie contains a session ID, the servlet generates
a new one using generateSessionId() and adds a cookie containing the new session ID
to the response.



No comments:

Post a Comment

Labels

(MCS-031 (6) 2011 (5) 4nf (1) 5nf (1) ACCESS CONTROL In Relational Database (1) ALGORITHMICS (5) assignment 2014 2015 (1) AVAILABLE TOOLS & ALGORITHMS (5) BCA (1) BINARY SEARCH (1) Block Nested Loop Join (1) Build and Fix Model (1) BUILDING BLOCKS OF ALGORITHMS (1) CHARACTERISTICS OF AN ALGORITHM (2) Core Java (1) Data Communication Network Security (1) DATABASE SECURITY (1) EER tool (1) ELEMEMTARY ALGORITHMICS (2) ENHANCED ER TOOLS (1) EVOLUTION (1) EXAMPLE OF AN ALGORITHM (2) Indexed Nested-Loop Join (1) install servelet engine (1) INTRODUCTION (1) Iterative Enhancement Model (1) Java Server Pages (1) JDBC (1) JSP (2) LEVELS OF DATABASE SECURITY (1) MCA (9) MCA 051 (1) MCA 3rd Semester (8) MCA 4th Semester (1) MCA 5 sem (1) MCS-031 (7) MCS-031 : DESIGN AND ANALYSIS OF ALGORITHM (14) MCS-032 (1) MCS-033 (1) MCS-034 (2) MCS-035 (1) mcs-041 (2) MCS-042 (1) mcs-043 (2) mcs-052 solved assignment (1) MCSL-036 (2) Nested loop join (1) OBJECTIVES (1) Operating System (2) OUTLINE OF ALGORITHMICS (1) Principles of Management and Information Systems (1) PROBLEMS (1) QUERY PROCESSING AND EVALUATION (1) Query processing Optimisation (1) Question Papers (8) Related Topic (9) relational Database (1) SELECT OPERATION Query Processing (1) Servlet (1) Servlet Programme (1) Servlet Programming (1) SOFTWARE DEVELOPMENT MODELS (4) SOFTWARE ENGINEERING (4) Solution (7) Solved Assignment 2013 2014 (6) SOME PRE-REQUISITES AND Asymptotic Bounds ASYMPTOTIC BOUNDS INTRODUCTION (1) STATISTICAL DATABASE SECURITY (1) structure (1) SUMMARY (1) Waterfall Model (1) Write a C program to print the following triangle (1)