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;
}
}
}