Logo         Community
  Trog
Services
The Company
Community
Columns
Your Account
Contact Us
 
 
The JSP Files (part 6): State Of Grace
Learn how to "maintain state" on a JSP-based Web site with the Cookie and Session objects.

| Learning To Write... |

Now, there are innumerable ways to go about creating and reading cookies on a client browser - you can use Javascript, you can use PHP, you can use any of the wonderful programming languages out there. However, our concern here is with JSP - so let's take a look at an example which demonstrates how to read and write a cookie.

This is a simple hit counter which creates a cookie the first time the user visits the Web page, and then increments the counter on each subsequent visit.


<%
// counter.jsp

// declare some variables
Cookie cookieCounter = null;

// the cookie you want
String cookieName = "counter";
int cookieFound = 0;

// a few more useful variables
String tempString;
int count=0;

// get an array of all cookies available on client
Cookie[] cookies = request.getCookies();

// iterate through array looking for your cookie
for(int i=0; i<cookies.length; i++)
{
    cookieCounter = cookies[i];
    if (cookieName.equals(cookieCounter.getName()))
   {
   cookieFound = 1;
    break;
   }
  
}

// if found
if(cookieFound == 1)
{

   // get the counter value as string
   tempString = cookieCounter.getValue();
  
   // convert it to a number
   count = Integer.parseInt(tempString);
  
   // increment it
   count++;
  
   // back to a string
   tempString = Integer.toString(count);
  
   // store it in the cookie for future use
   cookieCounter.setValue(tempString);
  
   // set some other attributes
   cookieCounter.setMaxAge(300);
   cookieCounter.setPath("/");

   // send cookie to client
   response.addCookie(cookieCounter);
}
// if not found
else
{
   // create a new cookie with counter 0
   Cookie alpha = null;
   alpha = new Cookie("counter", "0");
   alpha.setMaxAge(300);
   alpha.setPath("/");
   response.addCookie(alpha);
}
%>

<html>
<head>
<basefont face="Arial">
</head>

<body>

<%
// display appropriate message
if (count > 0)
{
out.println("You have visited this page " + count + " time(s)! Don't you have anything else to do, you bum?! ");
}
else
{
out.println("Welcome, stranger!");
}
%>

</body>
</html>


Sure, it looks a little complicated - but it won't once we break it down for you.

The first thing you need to know is how to create a cookie on the client - this is accomplished with the following code:


<%
Cookie alpha = null;
alpha = new Cookie("counter", "0");
alpha.setMaxAge(300);
alpha.setPath("/");
response.addCookie(alpha);
%>


The first two lines create a new instance of a Cookie object - "alpha". The cookie variable "counter" is then initialized and set to the string "0". Next, the setMaxAge() and setPath() methods of the Cookie object are used to set the expiry date (in seconds) and the cookie's availability, respectively. Finally, a call to the Response object's addCookie() method takes care of actually transmitting the cookie to the client.

As already mentioned, the only attribute which is not optional is the NAME=VALUE pair. If you'd like your cookie to remain available even after the user closes the browser, you should explicitly set an expiry date; if not, the cookie will be destroyed once the browser is closed.

The Cookie object also comes with a couple of other interesting methods.

setValue(someString) - sets the value of the cookie to someString

getValue() - returns the current value of the cookie

setPath(someURL) - sets the PATH attribute of a cookie to someURL

getPath() - returns the current value of the PATH attribute

setMaxAge(someSeconds) - sets the EXPIRES attribute of the cookie, in seconds

getMaxAge() - returns the current value of the EXPIRES attribute

setDomain(someURL) - sets the DOMAIN attribute of the cookie

getDomain() - returns the current value of the DOMAIN attribute

setSecure(flag) - sets the SECURE attribute of the cookie as either true or false

getSecure() - returns the current value of the SECURE attribute

Note that you can only save string values in a cookie with setValue() - which entails a lot of string-to-number-to-string conversions if you actually want to store a number (as in this example).


How to do Everything with PHP & MySQL
How to do Everything with PHP & MySQL, the best-selling book by Melonfire, explains how to take full advantage of PHP's built-in support for MySQL and link the results of database queries to Web pages. You'll get full details on PHP programming and MySQL database development, and then you'll learn to use these two cutting-edge technologies together. Easy-to-follow sample applications include a PHP online shopping cart, a MySQL order tracking system, and a PHP/MySQL news publishing system..

Read more, or grab your copy now!


previous page more like this  print this article  next page
 
Search...
 
In trog...
Logging With PHP
Building A Quick-And-Dirty PHP/MySQL Publishing System
Output Buffering With PHP
Date/Time Processing With PHP
Creating Web Calendars With The PEAR Calendar Class
more...
 
In the hitg report...
Crime Scenes
Animal Attraction
Lord Of The Strings
more...
 
In boombox...
Patience - George Michael
Think Tank - Blur
My Private Nation - Train
more...
 
In colophon...
Hostage - Robert Crais
The Dead Heart - Douglas Kennedy
Right As Rain - George Pelecanos
more...
 
In cut!...
American Chai
The Core
Possession
more...
 
Find out how you can use this article on your own Web site!


Copyright © 1998-2010 Melonfire. All rights reserved
Terms and Conditions | Feedback