dcsimg
October 21, 2018
Hot Topics:

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

  • October 19, 1999
  • 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



Comment and Contribute

 


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

 

 


Enterprise Development Update

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

By submitting your information, you agree that developer.com may send you developer offers via email, phone and text message, as well as email offers about other products and services that developer believes may be of interest to you. developer will process your information in accordance with the Quinstreet Privacy Policy.

Sitemap

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