How to delete cookies in jsp / java

This is my code to set a new cookie

Cookie citizen = new Cookie("citizen",email); citizen.setMaxAge(3600); response.addCookie(citizen); 

I now use this code to destroy the cookie

 Cookie[] cookies = request.getCookies(); for(int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("citizen")) { cookies[i].setMaxAge(0); response.addCookie(cookies[i]); } } 

But I still get the cookie value. Help will be appreciated!

+4
source share
5 answers

Below link can help you.

How to delete information from cookies?

Good luck !!!

Let me know about any further requests ...

+4
source

I had a problem like this when the cookie saved the value even after setting the maximum age to 0 and the value to "".

I used firefox to look at cookie attributes to help debug. Upon login, the servlet called my cookie class sets a cookie, and the path to the cookie is "/ javawork /". When logging out, the JSP page called the same cookie class โ€œdeletingโ€ the cookie, setting the maximum age to 0. But the JSP page was in a subfolder of the web application, so when I created the cookie of the same name with the maximum age of 0, it created a new cookie with the path / javawork / test _login / ".

So, the โ€œnewโ€ cookie immediately expired, but the original one still existed. In my delete cookie function, I needed to set the path of the โ€œnewโ€ cookie to โ€œ/ javawork /โ€, and when I set the maximum age to 0 and added it, it updated the original cookie and allowed me to log out correctly.

I hope this helps.

+1
source

Try adding this line:

  cookies[i].setMaxAge(0); //add this line cookies[i].setPath("/"); response.addCookie(cookies[i]); 
0
source

The correct option would be

 Cookie cookie = new Cookie("citizen", "citizen"); cookie.setMaxAge(0); cookie.setValue(""); response.addCookie(cookie); 

if you try to get a cookie from the request for the following, add it to the response using setMaxAge (0), you will see that the cookie has not been deleted.

0
source

It works for me -

 Cookie UIDCookie = new Cookie(COOKIE_KEY, ""); UIDCookie.setMaxAge(0); UIDCookie.setPath("/"); response.addCookie(qptUIDCookie); 
0
source

Source: https://habr.com/ru/post/1391610/


All Articles