Wednesday, June 22, 2011

Cookies in GWT

Google Web Toolkit (GWT) supports cookies similar to other web technologies. GWT provides methods for setting cookies for specified time duration, for specific domains and paths.

Below is a code to set a cookie for a duration of one day.
Date dt= new Date();
long dtlong = dt.getTime();
dtlong = dtlong + (1000 * 60 * 60 * 24);//setting cookie for one day
dt.setTime(dtlong);

//static method
Cookies.setCookie("cookieName", "cookieValue", dt);

When retrieving the cookies, you have to specify only the name of the cookie, nothing related to duration. If the cookie is found in the browser for this domain (not expired); value will be returned.
Cookies.getCookie("cookieName");//provide name as an argument

If the cookie does not exist, you should look for cookie before setting it again.
String strCookie = Cookies.getCookie("cookieName");
if(strCookie == null)
{
//set cookie again after informing user on expiration.
}