For more information on sites, see “Force.com Sites Overview” in the Salesforce online help.
The following example creates a class, CookieController, which is used with a Visualforce page (see markup below) to update a counter each time a user displays a page. The number of times a user goes to the page is stored in a cookie.
// A Visualforce controller class that creates a cookie // used to keep track of how often a user displays a page public class CookieController { public CookieController() { Cookie counter = ApexPages.currentPage().getCookies().get('counter'); // If this is the first time the user is accessing the page, // create a new cookie with name 'counter', an initial value of '1', // path 'null', maxAge '-1', and isSecure 'false'. if (counter == null) { counter = new Cookie('counter','1',null,-1,false); } else { // If this isn't the first time the user is accessing the page // create a new cookie, incrementing the value of the original count by 1 Integer count = Integer.valueOf(counter.getValue()); counter = new Cookie('counter', String.valueOf(count+1),null,-1,false); } // Set the new cookie for the page ApexPages.currentPage().setCookies(new Cookie[]{counter}); } // This method is used by the Visualforce action {!count} to display the current // value of the number of times a user had displayed a page. // This value is stored in the cookie. public String getCount() { Cookie counter = ApexPages.currentPage().getCookies().get('counter'); if(counter == null) { return '0'; } return counter.getValue(); } }
// Test class for the Visualforce controller @isTest private class CookieControllerTest { // Test method for verifying the positive test case static testMethod void testCounter() { //first page view CookieController controller = new CookieController(); System.assert(controller.getCount() == '1'); //second page view controller = new CookieController(); System.assert(controller.getCount() == '2'); } }
<apex:page controller="CookieController"> You have seen this page {!count} times </apex:page>
The following are constructors for Cookie.
public Cookie(String name, String value, String path, Integer maxAge, Boolean isSecure)
The following are methods for Cookie. All are instance methods.
public String getDomain()
Type: String
public Integer getMaxAge()
Type: Integer
public String getName()
Type: String
public String getPath()
Type: String
public String getValue()
Type: String
public Boolean isSecure()
Type: Boolean