Guide on Programming, Internet and Technology

DigiZol
| Contact

Set Cookies with GWT applications to expire after expected time period

Google Web Toolkit (GWT) supports HTTP cookies similar to other web technologies. GWT provides methods for setting cookies for specified time duration, for specific domains and paths. Below is a listing on how to set a basic cookie for a duration of one day.
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.}

Labels: , , ,

Translate into your language
Reader Comments
Comments Count: 2
Write your own opinion
Share with others
E-mail
Search More Articles
  1. Hi,

    Could 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
  2. I agree with Venkat

    Numero 5

Post a Comment

We appreciate your opinions, suggestions and criticism.

ABOUT AUTHOR
Kamal Mettananada is a Software Architect, Java Explorer and Blogger. Digizol consists of computer related articles, tutorials, tips and other information.
ARCHIVES
Select Month:

Free counter and web stats

FEED SUBSCRIPTION
Subscribe to our feed using your online news reader, approximately 1-2 articles per week.
ABOUT US
^top^