Working with Cookies on Sites pages in Summer ’10

Summer 10 introduces the ability to work with cookies on Force.com sites. This post provides a simple example to demonstrate how to use this new feature

The Summer '10 release is just around the corner, and the pre-release notes are now available. One of the new features of the release is the introduction of a new Cookie which lets you access cookies from a Force.com Sites page using apex. Cookies are often used to support the personalization of websites by storing textual information in the browsers cache. The result is, the Sites page 'knows' you have been here before and can perform some sort of logic as a result.

Let's look a simple example, taken from the docs (which includes full text and test cases which I omitted here for brevity), where we want to increment a counter each time the user has visited the page.

First our Apex Controller:

public class CookieController {
public CookieController()
{
Cookie counter = ApexPages.currentPage().getCookies().get('counter');
 
 if (counter ==null)
{
counter = new Cookie('counter','1',null,-1,false);
}
else
{
Integer count = Integer.valueOf(counter.getValue());
counter = new Cookie('counter', String.valueOf(count+1),null,-1,false);
}
 ApexPages.currentPage().setCookies(new Cookie[]{counter});
}
public String getCount()
{
Cookie counter = ApexPages.currentPage().getCookies().get('counter');
if(counter == null) {
  return '0';
}
return counter.getValue();
}
}

The code itself is pretty straight forward, but the important item to note is the way you can now retrieve cookies. The Apex PageReference class now includes a setCookies(Cookie) and getCookies() methods. These methods work very similar to the existing set/getParameters methods: retrieve a map of objects, cookies in this instance and return a specific instance based on a key, the name of the cookie.

In order to access the cookie from within our Visualforce page, all we need to do is call our getCount() method:

 You have seen this page {!count} times

This is a very simple example of using the Summer '10 feature of Cookies within Force.com Sites. Now with the ability to know when people have visited your site previously, the ability to react to, and customize the experiences really adds a lot more opportunity for innovation. But for now, I'm going to spend some time and keep looking through the pre-release notes, are you?

Leave your comments...

Working with Cookies on Sites pages in Summer ’10