Date now = new Date();
long nowLong = now.getTime();
nowLong = nowLong + (1000 * 60 * 60 * 24 * 7);//seven days
now.setTime(nowLong);
Cookies.setCookie("sampleCookieName", "sampleCookiValue", now);
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 you set will be returned.
Cookies.getCookie("sampleCookieName");//only name
In setting cookies, you must consider on what you actually plans to get done using a cookie. There are two features you can achieve; remember duration (i)from the day it's created, (ii) from the last day this particular user viewed your site. If your site always set cookies when ever a user visits your site; then your cookies will expire only after the user does not revisit your site for the specified duration. But if you are providing a feature like "Saving the password for 2 weeks", then you probably should store the cookie only if the cookie does not exists. For that you must look for cookie before setting it again.
String sampleValue = Cookies.getCookie("sampleCookieName");
if(sampleValue == null){
//set cookie again after informing user on expiration.}
Hi,
ReplyDeleteCould you please provide a sample program with setting and retrieving cookies,. it would be a great helpful for beginners like me in GWT.
Regards,
Venkat
I agree with Venkat
ReplyDeleteNumero 5
There is a bug in your code. Try the following:
ReplyDeletenowLong = nowLong + (1000 * 60 * 60 * 24 * 365);
that will result in setting the cookie in the past. You need to specify that you are using a long:
nowLong = nowLong + (1000l * 60l * 60l * 24l * 365l);
/José
/**
ReplyDelete* Saves the cookie with name "cookieTest".
*
*/
protected void saveTestCookie(final String value) {
final Date expireDtm = new Date(System.currentTimeMillis()
+ (1000 * 60 * 60 * 24 * 7)); /* seven days */
Cookies.setCookie("cookieTest", value, expireDtm, null,
null, true);
Cookies.setCookie("passwordValue", passwordValue, expireDtm, "www.mysite.com", null, true);
}
/**
* Gets the cookie value.
*/
private String getTestCookie() {
return Cookies.getCookie("cookieTest");
}
Thanks! It Helps!
ReplyDeleteTwo things I would add:
ReplyDelete1) it is dangerous not to user longs when adding milliseconds (if you are above 2^16 you will have an overflow resulting in a negative value, eg one month = 3600*1000*24*30>2^16-->you will add a negative value and therefore go in the past)
2) there is a simpler and cleaner way to get a future date:
new Date(System.currentTimeMillis()+(1000L*3600L*24L*30L))