Don Quixote
Don Quixote

Reputation: 4458

How to check whether a cookie has been set on previous visit?

In a java web application,I want to check whether a user who signs in is a returning user. How can I check if there is already a cookie that has been set on earlier login.

Upvotes: 0

Views: 7308

Answers (2)

AlexR
AlexR

Reputation: 115328

Set cookie when user performs log-in:

Cookie c = new Cookie("visit", "old")
c.setMaxAge(3600*24*365*1000); // 1 year (for example)
response.addCookie(new Cookie("visit", "old"));

Now you can check this cookie when user with new session comes to the system: request.getCookies(), then iterates over returned array and find "your" cookie. If cookie exists this is "old" user otherwise the new one.

Upvotes: 0

Estragon
Estragon

Reputation: 1462

On HttpServletRequest you have a getCookies() method that will give you an array of the cookies the client is sending with his request.

http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getCookies%28%29

Upvotes: 1

Related Questions