2. Cookies

It is sometimes necessary to use cookies for storing information on the client side. A cookie can be accessed from within an element, if the element definition contains an incookie or outcookie tag. An incookie is a cookie that can be read, and an outcookie can obviously be set.

Let's show how it works with a small example where we store the time when the user last visited a certain page. This is a typical real world example, and could be used for example to determine which news items are new since the last visit on a news site.

If we call our cookie last_visit and want to let the element NewsList get and set the cookie, the element definition would look like this:

Example 9.4. Defining an element with a cookie

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE element SYSTEM "/dtd/element.dtd">

<element implementation="NewsList">
  <incookie name="last_visit"/>
      
  <outcookie name="last_visit"/>
</element>      

Now that the element is allowed to access the cookie, we can write the Java code to read and write the cookie.

Example 9.5. NewsList.java: Using cookies from Java

package org.rifers.elephant.elements;

import com.uwyn.rife.engine.Element;

import javax.servlet.http.Cookie;
import java.util.*;
import java.text.*;

public class NewsList extends Element
{
  public void showNews(Date lastVisited)
  {
    // Print new news items
  }

  public void processElement()
  {
    Date date = Calendar.getInstance().getTime();
      
    if (hasCookie("last_visit"))
    {
      Cookie cookie = getCookie("last_visit");

      try
      {
        Date last = DateFormat.getInstance().parse(cookie.getValue());
        showNews(last);
      }
      catch (ParseException e)
      {
        // Handle exception
      }
    }
    else 
    {
      showNews(null);
    }

    setCookie(new Cookie("last_visit", 
              DateFormat.getInstance().format(date)));
  }
}      

Example 9.5, “NewsList.java: Using cookies from Java” uses both getGookie and setCookie. The cookie is first used to determine which news items to show and then set to the current time, to be used for the next visit.