This post helps Salesforce Developers to know how to use Apex Cookies.
Before going to depth. first we will familiar with the word cookie how and when to use it.
Cookies are small pieces of data that any website stores on your computer in order to pass that data between pages. Likewise APEX also gives us the ability to use cookies, however APEX cookies are little bit different than the normal cookies that we get in the browser. For APEX the cookie is a class that we can use to set data in a Pagereference variable so that it can be used later on. This is what I will demonstrate, how to use cookie class of APEX.
Cookie Class Functions
The default cookie class gives us multiple functions to use for accessing cookies like:
- getName() – This function returns the name of the cookie that the class has.
- getValue() – This function provides the value of the cookie string.
- isSecure() – Returns true if the cookie can only be accessed by HTTPS, else false.
1)setcookies variable in apex:
public class cookie { public string Data { get; set;} public pagereference setData(){ Pagereference pr = new Pagereference('/apex/yourpagename'); Cookie cookietest = new Cookie('value', Data, null, -1, false); pr.setCookies(new Cookie[] {cookietest}); return pr; } }
In the above class we have a simple pagereference method in which we have created a cookie object and to the constructor we have passed various arguments. The first argument is the name of the cookie, that we will use to access the cookie later on. Second argument is the actual value which will be passed into the cookie. The third variable is the path, which specifies where the cookie will be stored. Setting the path to null will just store the cookie in root. Next argument specifies the lifespan of the cookie. To set a normal lifespan pass any positive value to the cookie. Setting the value to 0 will destroy the cookie. A negative value will make the cookie a session cookie and will end with the session. The last argument specifies whether the cookie can only be retrieved by secure method, i.e. HTTPS or not.
After creating the cookie we have to set it in the pagereference variable by the setcookies method. This method takes a list of cookie type as input so we have passed the object as a list.
2) Get cookie variable :
public class yourvfpagecontroller { public string data { get; set;} public yourvfpagecontroller (){ data = apexpages.currentPage().getCookies().get('value').getValue(); system.debug(data); } }
Once we get it we can show it on the VF page. We can even show it on any page within the org by simply using the above command in apex controller. The cookie will be available for the provided lifespan.
Hits: 1316