Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Creating a Cookie

This next example will put all this new technology to work. Here, the code will create a cookie and place some text in it, and another page will read the cookie and display that text. To create the cookie, you use the Cookie class's constructor, passing it the name of the cookie (which will be message here) and the text in the cookie (which will just be "Hello!" in this case). You can also set the length of time the cookie will exist on the user's computer with the setMaxAge method, which you pass a value in seconds to—to make the cookie last for a day, you can pass a value of 24 * 60 * 60 this way:

<HTML>
  <HEAD>
    <TITLE>Setting a Cookie</TITLE>
  </HEAD>

  <BODY>
    <H1>Setting a Cookie</H1>
 
    <%
    Cookie cookie1 = new Cookie("message", "Hello!");
    cookie1.setMaxAge(24 * 60 * 60);
    %>
    .
    .
    .

That creates the cookie, but doesn't install it in the browser—to do that, you use the response object's addCookie method this way:

<HTML>
  <HEAD>
    <TITLE>Setting a Cookie</TITLE>
  </HEAD>

  <BODY>
    <H1>Setting a Cookie</H1>
 
    <%
    Cookie cookie1 = new Cookie("message", "Hello!");
    cookie1.setMaxAge(24 * 60 * 60);
    response.addCookie(cookie1);
    %>
    .
    .
    .

That installs the cookie in the browser. You can also include a link to the page that will read the cookie, as you see in Listing 7.2.

Listing 7.2 Setting a Cookie (ch07_02.jsp)

<HTML>
  <HEAD>
    <TITLE>Setting a Cookie</TITLE>
  </HEAD>

  <BODY>
    <H1>Setting a Cookie</H1>
 
    <%
    Cookie cookie1 = new Cookie("message", "Hello!");
    cookie1.setMaxAge(24 * 60 * 60);
    response.addCookie(cookie1);
    %>
  
    <A HREF="ch07_03.jsp"/>Read the cookie</A>
  </BODY>
</HTML>

You can see this page in Figure 7.3, where it's already set its cookie in the browser. The next step is to read that cookie's information back in.

Figure 7.3Figure 7.3 Setting a cookie.

  • + Share This
  • 🔖 Save To Your Account