Home > Articles > Programming > Java

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

Reading a Cookie

To store a cookie in the user's computer, you use the request object's getCookies method. This method returns an array of Cookie objects (or null if there are no cookies) So how do you read the cookie named message? You start with the getCookies method, creating an array of Cookie objects:

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

  <BODY>
    <H1>Reading a Cookie</H1> 
 
    <%
    Cookie[] cookies = request.getCookies();
    .
    .
    .

TIP

Are you passed all the cookies on the computer? No, you're only passed the cookies that came from the same domain as the page you're using the getCookies method in.

This returns an array of cookies, which you can loop over to find the message cookie. Here's what that loop might look like:

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

  <BODY>
    <H1>Reading a Cookie</H1> 
 
    <%
    Cookie[] cookies = request.getCookies();
  
    for(int loopIndex = 0; loopIndex < cookies.length; loopIndex++) {
      .
      .
      .
    } 
    .
    .
    .

Inside the body of the loop, you can get the name of each cookie with the Cookie class's getName method, and its value with the getValue method. If the code finds the message cookie, it displays that cookie's value. You can see what that looks like in Listing 7.3.

Listing 7.3 Reading a Cookie (ch07_03.jsp)

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

  <BODY>
    <H1>Reading a Cookie</H1> 
 
    <%
    Cookie[] cookies = request.getCookies();
  
    for(int loopIndex = 0; loopIndex < cookies.length; loopIndex++) { 
      if (cookies[loopIndex].getName().equals("message")) {
        out.println("The cookie says " + cookies[loopIndex].getValue());
      }
    } 
    %>
  </BODY> 
</HTML> 

Now this page is able to read the cookie set in ch07_02.jsp. You can see what the results are in Figure 7.4, where the code was able to recover and display the cookie's text.

Figure 7.4Figure 7.4 Reading a cookie.

Now you're setting and reading cookies using JSP!

  • + Share This
  • 🔖 Save To Your Account