Home arrow Java & J2EE arrow Page 4 - The JSP Files (part 6): State Of Grace

Learning To Write... - Java

Now that you've mastered the basics, it's time to bring out thebig iron. This week, The JSP Files explores the various techniquesavailable to "maintain state" on a JSP-based Web site. Learn about theCookie and Session objects, find out how to build a cookie-based hitcounter, and read about a simple yet effective way of protecting sensitiveWeb pages with the Session object.

TABLE OF CONTENTS:
  1. The JSP Files (part 6): State Of Grace
  2. Wasted, Dude!
  3. A Few Ground Rules
  4. Learning To Write...
  5. ...And Read
  6. What's In A Name?
  7. Plan B
  8. Session Dissection
  9. Access Denied
By: Vikram Vaswani and Harish Kamath, (c) Melonfire
Rating: starstarstarstarstar / 5
March 26, 2001

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

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

This is a simple hit counter which creates a cookie the first time the uservisits the Web page, and then increments the counter on each subsequentvisit.

<% // 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 downfor 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". Thecookie variable "counter" is then initialized and set to the string "0".Next, the setMaxAge() and setPath() methods of the Cookie object are usedto set the expiry date (in seconds) and the cookie's availability,respectively. Finally, a call to the Response object's addCookie() methodtakes care of actually transmitting the cookie to the client.

As already mentioned, the only attribute which is not optional is theNAME=VALUE pair. If you'd like your cookie to remain available even afterthe user closes the browser, you should explicitly set an expiry date; ifnot, 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, inseconds

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 orfalse

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 youactually want to store a number (as in this example).

 
 
>>> More Java & J2EE Articles          >>> More By Vikram Vaswani and Harish Kamath, (c) Melonfire
 

blog comments powered by Disqus
   

JAVA & J2EE ARTICLES

- More Java Bugs Lead to More Attacks
- Oracle's Java One Brings News, Surprises
- Oracle Patches Java Runtime Environment
- Apple Syncs Java Update with Oracle
- Spring 3.1 Java Development Framework Compat...
- Jelastic Java PaaS Availability and Pricing ...
- NetBeans 7.1 Released, Supports JavaFX 2
- SolarWinds Releases Newest Version of Java M...
- Free Monitoring Tool for Java Apps on Heroku
- Heroku Adds JCloud Platform Support, Java 7 ...
- Java SE 8 Speculation in Full Swing
- Java SE 7 Now Available
- New JVM Language and Java Reporting Tool
- Java 7 Release Update and New Eclipse Toolkit
- The Best Java Netbeans IDE Plugins

Developer Shed Affiliates

 



© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap

Dev Shed Tutorial Topics: