Java
  Home arrow Java arrow Page 3 - Saving Client State with Cookies and Java
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
JAVA

Saving Client State with Cookies and Java
By: Kulvir Singh Bhogal
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 52
    2004-03-24


    Table of Contents:
  • Saving Client State with Cookies and Java
  • Some Background Information About Cookies
  • Setting Cookies on Your Client
  • Grabbing Cookies From Your Client
  • Throwing JavaScript Into the (Cookie Dough) Mix
  • Cleaning Up: Getting Rid of Cookie Crumbs

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Saving Client State with Cookies and Java - Setting Cookies on Your Client
    ( Page 3 of 6 )

    CookieSetterServlet is one of the servlets you will find in the EAR.  You can find the code for this servlet in Listing 1. 


    import java.io.IOException;
    import java
    .io.PrintWriter;
    import javax
    .servlet.Servlet;
    import javax
    .servlet.ServletException;
    import javax
    .servlet.http.Cookie;
    import javax
    .servlet.http.HttpServlet;
    import javax
     
    .servlet
     
    .http
     
    .HttpServletRequest;
    import javax
     
    .servlet
     
    .http
     
    .HttpServletResponse;
     
    public class 
    CookieSetterServlet
     
    extends HttpServlet
     
    implements Servlet
    {
     
    public void doGet(
      HttpServletRequest request
    ,
      HttpServletResponse response
    )
      throws ServletException
    IOException
     
    {
      
    // grab the user's favorite cookie type from the request
      String favoriteCookieType =
       request.getParameter(
        "FavoriteCookiePreference");
      // report the value to the console
      System.out.println(
       "Setting favorite cookie type to: "
        + favoriteCookieType);
      // create a new Cookie object.  
      // set the token name to "FavoriteCookieType"
      // set the value to the value extracted from the request
      Cookie favoriteCookie =
       new Cookie(
        "FavoriteCookieType",
        favoriteCookieType);
      // set the value of the comment
      favoriteCookie.setComment(
       "Houses User's Favorite Cookie Type");
      // add the cookie to the response
      response.addCookie(
       favoriteCookie);
      // provide some visual feedback to the user
      PrintWriter out =
       response.getWriter();
      out.println(
       " "
        + "");
      out.println(
       " 
    <H2>I am now going to "remember" that you like "
        + favoriteCookieType
        + " 
    cookiesusing Cookies.</H2>");
      out.println("");
     }
     public void doPost(
      HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException
     {
      doGet(request, response);
     }
    }


    Listing 1: CookieSetterServlet.java

    The servlet grabs a parameter from the request named FavoriteCookiePreference.    Note that the HTML file, favoritecookie.html calls the servlet and feeds the servlet with request data (see Figure 3).

    Client State with Cookies in Java

     
    Figure 3: favoritecookie.html Feeds
    CookieSetterServletwith Request Data

    Our code to create a cookie on the server side and send it back to the client is a straightforward process.  We simply create a new Cookie object by calling the constructor with the name of the cookie we want to create and its associated value (the value we collected from our request). 

    In the code, we also set a comment for the cookie.  Finally, the resulting Cookie object is packaged to be shipped back to the client by calling the Response object’s addCookie method, which takes our new Cookie as an argument.

    For some visual feedback, the servlet reports to the user what was extracted from the request (see Figure 4).


    Client State with Cookies in Java

    Figure 4: Output of the CookieSetterServlet
    Servlet, After Sending the Cookie to the Client

    It is important to note that we added the cookie to our Response object before using our PrintWriter object. This order is mandatory if you want things to work. Your cookie is going to be sent back to the client as a header; headers must be written before accessing the PrintWriter.

    It is also important to note that the cookies that a server places on a client are associated only to that server. 

    Coming up, we’ll use a different servlet to grab our cookie’s value from the client.  Note that since this second servlet will reside on the same server as our first servlet, we are able to access the client cookie we established (which we named FavoriteCookieType).



     
     
    >>> More Java Articles          >>> More By Kulvir Singh Bhogal
     

       

    JAVA ARTICLES

    - Exception Handling Techniques in Java
    - More About Multithreading in Java
    - The Basics of Multiple Threads in Java
    - Data Access Using Spring Framework JDBC
    - New Object Initialization in Java
    - Adding Images With iTextSharp
    - Adding Columns With iTextSharp
    - Creating Simple PDF Files With iTextSharp
    - The Spring Framework: Understanding IoC
    - Introducing the Spring Framework
    - Java Classes
    - Completing the Syntactic Comparison of Java ...
    - Syntactic Comparison of Java and C/C++
    - Java Statements
    - Conditionals, Expressions and Other Java Ope...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek