- Forward


Cookie Handling in Java
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Review
Back SMYC Forward
  • Purpose of Cookies in HTTP:
    • Allow for the preservation of state information
  • Internals:
    • Name-Value pairs
  • Transmission:
    • In a Request: Use a Cookie header
    • In a Response: Use a Set-Cookie header
Encapsulating Cookies
Back SMYC Forward
  • The Class:
    • HttpCookie
  • Obvious Methods:
    • getName()
    • getValue()
  • Methods for Retrieving Attributes:
    • getDiscard()
    • getDomain()
    • getMaxAge()
    • getPath()
Managing Cookies
Back SMYC Forward
  • The CookieHandler Interface:
    • get() gets all applicable cookies from the cache
    • put() sets all applicable cookies
    • set() is a static method that sets the universal cookie handler for all subsequent HTTP connections
  • The CookieManager Class:
    • A concrete implementation provides security and uses a CookieStore to save/retrieve the cookies
  • The CookieStore Interface:
    • The requirements of an object that can save/retrieve cookies
An Example
Back SMYC Forward

Display the Cookies Set by an HTTP Response

javaexamples/internet/DisplayCookies.java
 
Providing Persistence
Back SMYC Forward
  • What's Needed:
    • A class that implements CookieStore (and probably Runnable for reasons discussed below)
  • When to Load/Save?
    • Loading should happen at construction time
    • Saving depends on the application
  • Ensuring a Save at Shutdown:
    • Call Runtime.getRuntime().addShutdownHook() and pass it a Thread (with an associated Runnable)
There's Always More to Learn
Back -