April 17, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

State and session tracking with Java servlets Part 1: Using cookies, Page 2

  • October 19, 1999
  • By David Reilly, David Reilly
  • Send Email »
  • More Articles »

  Listing 1
Putting cookies to work
by David Reilly.

 

// Import io package
import java.io.*;

// Import servlet packages
import javax.servlet.*;
import javax.servlet.http.*;


public class CookieCounter extends HttpServlet
{

 // GET request handler
 public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException
 {
  // Define content type
  response.setContentType("text/html");
 
  PrintStream pout = new PrintStream(response.getOutputStream());

  // Check to see if there are any cookies
  Cookie[] cookieArray = request.getCookies();

  // Default value
  int count = 0;

  // Check for cookies
  if (cookieArray != null)
  {
   for (int i =0; i< cookieArray.length; i++)
   {
    Cookie c = cookieArray[i];

    // Check for the count cookie
    if (c.getName().equals("count"))
    {
     // Parse cookie value and assign to count
     try
     {
      Integer num = new Integer (c.getValue());
      count = num.intValue();
     }
     catch (NumberFormatException nfe) {}
    }
   }
  }

  // Increment counter
  count++;

  // Send updated cookie
  response.addCookie(new Cookie ("count", String.valueOf(count)));

  // Output message
  pout.println ("You have visited this page " + count +
   " times since your web browser started");
  pout.flush();
 }

 // POST request handler calls GET request handler
 public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException
 {
  doGet(request,response);
 }

}





Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel