Setting and Getting Cookies

Cookies are string variables that the Web Browser stores on the user's client machine. Here are two JSP's, the first that stores cookies, and second that retrieves the cookies.

<%
   // setCookies.jsp
   Cookie c1 = new Cookie("NewJersey","Trenton");
   Cookie c2 = new Cookie("NewYork","Albany");
   response.addCookie(c1);
   response.addCookie(c2);
   out.println("Cookies set for capitals of New Jersey and New York");
%>
 

--------------

<%
   // getCookies.jsp
   // declare some variables
   Cookie cookie = null;
   String cookieName = null;
   String cookieValue = null;
   // the cookie you want
   String state1 = "NewYork";
   String state2 = "NewJersey";
   String capital1 = "not found";
   String capital2 = "not found";
   // get an array of all cookies available on client
   Cookie[] cookies = request.getCookies();
   // iterate through array looking for our cookies
   for(int i=0; i<cookies.length; i++)
   {
      cookie = cookies[i];
      cookieName = cookie.getName();
      cookieValue = cookie.getValue();
      if (state1.equals(cookieName)){
        capital1 = cookieValue;
      }
      if (state2.equals(cookieName)){
       capital2 = cookieValue;
      }
   }
   out.println("The capital of " + state1 + " is " + capital1    + "<BR>");
   out.println("The capital of " + state2 + " is " + capital2);
%>