Dashboard > RIFE > ... > Web engine > Cookies
RIFE Log In | Sign Up   View a printable version of the current page.
Cookies


Added by Steven Grimm, last edited by Joshua Hansen on Aug 23, 2007  (view change)
Labels: 
(None)

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:

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.

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);
    }
    Cookie cookie = new Cookie("last_visit", DateFormat.getInstance().format(date));
    cookie.setMaxAge(10*365*24*60*60); // Persistent cookie that expires ten years from today 
    setCookie(cookie);
  }
}

The example above 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.



Are you enjoying Confluence? Please consider purchasing it today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.2.1a Build:#515 May 19, 2006) - Bug/feature request - Contact Administrators