Pages

Tuesday, July 26, 2011

Example: Setting and Retreiving Cookies

In this example, I'm setting a cookie with its value obtained from the "Name" input box when the user clicks on "Add Cookie." When the user clicks on "Show Cookie," the cookie is retrieved, the panel is refreshed, and the name should be displayed. When the user clicks on "Validate Cookie," the cookie's maxAge is looked at. If the cookie hasn't expired, the user is taken to an Apex page named, "not_expired" and alternately "expired" if the cookie is no longer valid.




VF:
<apex:outputPanel id="CookieTest">
   <apex:form >
      Name:<apex:inputtext value="{!Name}"/>
      <br />
      <apex:commandButton action="{!addtocookie}" value="Add to Cookie"/>
      <apex:commandButton action="{!ShowCookie}" value="ShowCookie" rerender="CookieTest"/>
      <apex:commandButton action="{!ValidateCookie}" value="ValidateCookie"/>
      <br />
      The Name set in the cookie is : {!NameAtCookie}<br />
      Max Age: {!MaxAge}
   </apex:form>
</apex:outputPanel>

Class:
public with sharing class testCookie {
   public string Name{get; set;}
   public string NameAtCookie{get; set;}
   public integer maxAge{get; set;}
   public testCookie(test controller) {
   }
   public Pagereference addToCookie(){
      InsertValueToCookie(Name);
      return null;
   }

   public Pagereference ValidateCookie(){
      SetCookieToNameAtCookies();
      if(NameAtCookie == 'expired'){
         pageReference pageRef = new pageReference('/apex/expired');
         return pageRef;
      }
      else{
         pageReference pageRef = new pageReference('/apex/not_expired');
         return pageRef;
      }
   }
   public Pagereference ShowCookie(){
      SetCookieToNameAtCookies();
      return null;
   }
   public void InsertValueToCookie(string val){
   /* create a new cookie with name 'counter', an initial value of Name at the page,
path 'null', maxAge '-1', and isSecure 'false'.*/
      Cookie myCookies=new Cookie('mycookie',val,null,-1,false);
      ApexPages.currentPage().setCookies(new Cookie[]{myCookies});
   }

   public void SetCookieToNameAtCookies(){
   /* reading the value of the cookie 'mycookie' , and insert him to 'NameAtCookie' field */
      Cookie myCookies = ApexPages.currentPage().getCookies().get('mycookie');
      if(myCookies != null){
         NameAtCookie=myCookies.getValue();
         maxAge=myCookies.getMaxAge();
      }
      else{
         NameAtCookie='expired';
         maxAge=null;
      }
   }
}