Get cookie value in java

Tags: ,



I’ve initialized cooke like this in my JSP,

String timeStamp = new SimpleDateFormat("dd:MM:yyyy_HH:mm:ss:SSS").format(Calendar.getInstance().getTime());
timeStamp = timeStamp + ":" + System.nanoTime();
String loc = "/u/poolla/workspace/FirstServlet/WebContent/WEB-INF/"+timeStamp;
Cookie thecookie = new Cookie("thecookie", loc);
thecookie.setMaxAge(60*60*24);
response.addCookie(thecookie);

So, all the cookies created will have the same name, but different value for different user access time.

At the ending of java servlet I want to deactivate/kill the cookie that has been passed at the beginning of java servlet and say if they are 5 users using the system in parallel how will I know which cookie to deactivate for which user in the last of my.java?

for example, consider

User 1 : cookie name `thecookie` value `AAA`
User 2 : cookie name `thecookie` value `BBB`
User 3 : cookie name `thecookie` value `CCC`
User 4 : cookie name `thecookie` value `DDD`
User 5 : cookie name `thecookie` value `EEE`

Now, at the end of my.java servlet I want to deactivate the cookie with value CCC that has been assigned at the beginning of my.java without disturbing other cookie values, how to do this?

Answer

You are using the wrong method for reading the cookies..

Cookie[] cookies = request.getCookies();

if (cookies != null) {
 for (Cookie cookie : cookies) {
   if (cookie.getName().equals("cookieName")) {
     //do something
     //value can be retrieved using #cookie.getValue()
    }
  }
}

use this. No need to detect the cookie for particular user just deactivate it.



Source: stackoverflow