Cookies in Servlets


Cookies are small bits of textual information that a Web server sends to a browser and that the browser later returns unchanged when visiting the same Web site or domain. The server read information it sent the client previously. The site can provide visitors with a number of conveniences such as presenting the site the
way the visitor previously customized it or letting identifiable visitors in without their having to reenter a password.


Benefits of Cookies
  1. Identifying a user during an e-commerce session
  2. Remembering usernames and passwords
  3. Customizing sites
  4. Focusing advertising
Sending Cookies to the Client

1. Creating a Cookie object. You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.

2. Setting the maximum age. If you want the browser to store the cookie on disk instead of just keeping it in memory, you use setMaxAge to specify how long (in seconds) the cookie should be  valid.

3. Placing the Cookie into the HTTP response headers. You use response.addCookie to accomplish this. If you forget this step, no cookie is sent to the browser


Using Cookies to Detect  First-Time Visitors-Example

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Servlet that says "Welcome aboard" to first-time
 *  visitors and "Welcome back" to repeat visitors.
 *  Also see RepeatVisitor2 for variation that uses
 *  cookie utilities from later in this chapter.
 */
public class RepeatVisitor extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    boolean newbie = true;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
      for(int i=0; i
        Cookie c = cookies[i];
        if ((c.getName().equals("repeatVisitor")) &&
            // Could omit test and treat cookie name as a flag
            (c.getValue().equals("yes"))) {
          newbie = false;
          break;
        }
      }
    }
    String title;
    if (newbie) {
      Cookie returnVisitorCookie =
        new Cookie("repeatVisitor", "yes");
      returnVisitorCookie.setMaxAge(60*60*24*365); // 1 year
      response.addCookie(returnVisitorCookie);
      title = "Welcome Aboard";
    } else {
      title = "Welcome Back";
    }
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String docType = "
      "Transitional//EN\">\n";
 out.println(docType + "\n" + title + "\n" );
  }
}

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

0 comments:

Post a Comment