dcsimg
September 30, 2020
Hot Topics:

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

  • By 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



This article was originally published on October 19, 1999

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.


Thanks for your registration, follow us on our social networks to keep up-to-date