Sometimes there is a need to access cookies on a client-machine to save some data. JSP represents cookies with a Cookie object. A cookie is normally composed of several attributes. The most important data is the name-value pair, which is the data the server would retrieve from the cookie. But the cookie also contains information on when to expire the cookie and when to give out the cookie.

The sample page below shows an example of getting and setting cookies. This uses cookies to keep the name of the user loggen in:

<%@ page import ="java.util.*">
  /** this function converts an array of cookies into a hashtable */
  Hashtable cookieTable(Cookie[] cookies) {
    Hashtable cookieTable = new Hashtable();
    if (cookies != null) {
      for (int i=0; i < cookies.length; i++)
        cookieTable.put(cookies[i].getName(), cookies[i].getValue());
    return cookieTable;
  Cookie myCookie;
  String username = new String();
  Hashtable cookies = cookieTable(request.getCookies());

  String newLogin = request.getParameter("name");
  if (cookies.containsKey("name")) {
    username = (String)cookies.get("name");

  if (newLogin != null) {
    if (newLogin.equals("")) {
      myCookie = new Cookie("name""");
      username = null;
    else {
      myCookie = new Cookie("name", newLogin);
      username = newLogin;


  <body bgcolor="#ffffff">

  <% if (username == null || username.equals("")) { %>

    You look like a new user! <br />
    <form method="get" action="<%= request.getRequestURI()%>">
      Enter your name to create login : <br />
      <input type="text" size="8" name="name" />
      <input type="submit" value="login" />

  <% else %>

    Welcome back, <%= username %> <br />
    <%= new java.util.Date() %>

    <form method="get" action="<%= request.getRequestURI()%>">
      Enter your name to create login : <br />
      <input type="hidden" name="name" value=""  />
      <input type="submit" value="logout" />

  <% %>