Skip to content

Instantly share code, notes, and snippets.

@tyoshikawa1106
Last active December 3, 2017 11:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyoshikawa1106/5797040 to your computer and use it in GitHub Desktop.
Save tyoshikawa1106/5797040 to your computer and use it in GitHub Desktop.
CookieをApexで扱うときのサンプル : [参考サイト] http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_sites_cookie.htm
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});
}
/*
* Cookieから情報取得
*/
public String getCount() {
Cookie counter = ApexPages.currentPage().getCookies().get('counter');
return counter == null ? '0' : counter.getValue();
}
/*
* Cookieの情報をクリア
*/
public void doClear() {
Cookie counter = new Cookie('counter', String.valueOf(0), null, -1, false);
ApexPages.currentPage().setCookies(new Cookie[]{counter});
}
}
@isTest
private class CookieControllerTest {
static testMethod void CookieControllerTest() {
Test.startTest();
CookieController cls = new CookieController();
System.assertEquals(cls.getCount(), '1');
cls = new CookieController();
System.assertEquals(cls.getCount(), '2');
Test.stopTest();
}
static testMethod void doClearTest() {
Test.startTest();
CookieController cls = new CookieController();
cls.doClear();
System.assertEquals(cls.getCount(), '0');
Test.stopTest();
}
}
<apex:page controller="CookieController" showHeader="true" sidebar="false" id="page">
<apex:sectionHeader title="Cookie Sample"/>
<apex:form id="form">
<apex:pageBlock >
<apex:pageBlockButtons location="top">
<apex:commandButton value=" Clear " action="{!doClear}" reRender="form"/>
</apex:pageBlockButtons>
<apex:pageBlockSection >
<apex:pageBlockSectionItem >
<apex:outputText value="表示回数" />
<apex:outputText value="{!Count}" />
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment