How do you remove a Cookie in a Java Servlet
The MaxAge of -1 signals that you want the cookie to persist for the duration of the session. You want to set MaxAge to 0 instead.
From the API documentation:
A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.
deleting a cookie using java
You need to set the very same cookie with a null
value and a max age of 0
(and the same path, if you have set a custom one) back on the response by HttpServletResponse#addCookie()
.
cookie.setValue(null);
cookie.setMaxAge(0);
cookie.setPath(theSamePathAsYouUsedBeforeIfAny);
response.addCookie(cookie);
Unrelated to the concrete problem, you do not need massage the array to a list and back at all. The enhanced for loop works on arrays as good. Also, using ==
to compare Long
values would only work for values between -128 and 127. You need equals()
instead. So all in all, the method could look like this:
public void delete(MyType instance) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (Long.valueOf(cookie.getValue()).equals(instance.getId())) {
cookie.setValue(null);
cookie.setMaxAge(0);
cookie.setPath(theSamePathAsYouUsedBeforeIfAny);
response.addCookie(cookie);
}
}
}
}
By the way, it's scary to see request
and response
being instance variables of some class. Are you sure that the particular class is threadsafe? To understand servlets and threadsafety, you may find this answer helpful: How do servlets work? Instantiation, sessions, shared variables and multithreading.
Problem removing cookie in servlet
The problem was that the cookie I wanted to remove had a path that was "/admin" and my logout servlet had the path "/admin/logoutServlet". When I get the cookie from the request the path is set to null. So when I add the cookie the path is set to "/admin/" as my servletIf I created a cookie with the path "/admin/" the servlet was able to remove it.
I solved the problem by explisitly setting the path of the cookie before adding it to the response.
minIdCookie.setMaxAge(0);
minIdCookie.setPath("/");
res.addCookie(minIdCookie);
But I don't understand why the path is null.
cannot delete cookies from servlet
If you can get it, you can change it !
You have to add it to the answer.
HttpServletResponse resp
Cookie[] cookies = request.getCookies();
Cookie the_cookie // get the good one !
the_cookie.setMaxAge(0);
resp.addCookie(the_cookie);
or see that: How do you remove a Cookie in a Java Servlet
How to remove a cookie
Cookies are tied to a specific path. You need to make sure that you set the same path during cookie's removal as it was as during cookie's creation. It defaults to the currently requested folder in the URL (and would thus only be available in the same folder or all its subfolders). You'd better explicitly specify the path, otherwise it would be dependent on the currently requested folder in the URL. The cookie path information is like the maxage namely not available in the request cookie header.
Assuming that you created the cookie as follows,
Cookie cookie = new Cookie("CookieForLogin", cookieForLogin);
cookie.setPath("/somePath");
cookie.setMaxAge(maxAgeInSeconds);
// ...
response.addCookie(cookie);
it needs to be removed as follows:
Cookie cookie = new Cookie("CookieForLogin", null);
cookie.setPath("/somePath");
cookie.setMaxAge(0);
// ...
response.addCookie(cookie);
The /somePath
is just exemplary. You can also just use /
, as long as it's the same in both cases.
Note, the same applies to the Secure and HTTP-only flags of the cookie. If you have initially set it to true
during cookie's creation, then you should also set it to true
during cookie's removal, they namely defaults to false
.
That said, I'm not sure how it's useful to store the logged-in user as a cookie. You're basically also allowing the enduser to manipulate its value. Rather just store the logged-in user as a session attribute instead and call session.invalidate()
on logout.
how to delete the cookies in jsp/java
below link might help you..
How can delete information from cookies?
Good Luck!!!
Let me know incase of any further queries...
Delete cookie from a servlet response
Setting the maximum age to 0
is right. But it must have exactly the same other cookie properties, except of the value. Thus exactly the same domain, path, secure, etc. The value is optional, it can best be set to null
.
So, given the way how you created the cookie,
Cookie cookie = new Cookie("user", user);
cookie.setPath("/MyApplication");
cookie.setHttpOnly(true);
cookie.setMaxAge(3600);
response.addCookie(cookie);
it needs to be removed as follows:
Cookie cookie = new Cookie("user", null); // Not necessary, but saves bandwidth.
cookie.setPath("/MyApplication");
cookie.setHttpOnly(true);
cookie.setMaxAge(0); // Don't set to -1 or it will become a session cookie!
response.addCookie(cookie);
That said, I'm not sure how it's useful to store the logged-in user as a cookie. You're basically also allowing the enduser to manipulate its value. Rather just store it as a session attribute instead and call session.invalidate()
on logout.
How to remove cookies in servlets on window close or while application re-run is happening
First of all, it's important to differentiate between a cookie on the client side, and a session on the server side (I think you already knew that).
Usually, for a clean logout, you'll want to call session.invalidate()
on the servers side, and Cookies.removeCookie(...)
on the client side.
But not every 'logout' is clean:
- The logout request may not make it to the server
- The browser may crash even before you call removeCookie - so any attempt to remove a cookie on window close will be unreliable
On the server side, you can use timeouts (see the link provided by @thinksteep: How we call logout servlet on browser close event).
For the client side cookie, you can set an expiryDate/maxAge. Or you can use "session cookies": These are the cookies where you don't set expiry or maxAge at all. Most browsers will delete "session cookies" automatically when the browser restarts - but please see Firefox session cookies.
All of this may mean, that cookies are maybe not the best technology for your use case: In general, a cookie is by design available in all browser tabs, and the concept of a browser session doesn't even always end, when the browser/window closes (what would it mean on a smartphone anyway?). This is desirable for many current web sites (users don't have to log in explicitly every time), and many users have come to expect this kind of behavior.
For sites that want a "one tab = one session" policy, it's possibly better to store a token e.g. in a Javascript (or GWT) object, and send it with every request. This way, you can log in separately - even as different users - from multiple browser tabs, and once a tab closes, the token is gone. Please note, that a tab may still get restored by the browser on session restore. (I would always combine this technique with a httponly cookie, to avoid certain kinds of attacks.)
Java Servlet : Cookies do not get deleted
Update
As per Problem removing cookie in servlet
The path and domain will always be null when you retrieve cookies in Java because they are only necessary in the response for the client browser. However, if you're in the same security domain (regardless of the path), you still have the rights to delete them. Unfortunately, because the path is not included you can't delete the cookie now without explicitly knowing that path. Simply using the same cookie name, but a different path will not work. Those are considered two different cookies, and you will find that instead of deleting the cookie, you just created another one on a different path.
So you should not change value or path as this will create a new cookie
Related Topics
Parsing Xml with Regex in Java
How to Find the Sum of All the Numbers in an Array in Java
Is There a Fixed Sized Queue Which Removes Excessive Elements
What Does It Mean to Program to an Interface
Package Conflicts with Automatic Modules in Java 9
Check Whether Number Is Even or Odd
"Detached Entity Passed to Persist Error" with JPA/Ejb Code
Spring Data JPA Update @Query Not Updating
Java 8 Date and Time: Parse Iso 8601 String Without Colon in Offset
How to Read JSON File into Java with Simple JSON Library
How to Remove a Cookie in a Java Servlet
Is There an Upper Bound to Biginteger
Is Java.Util.Date Using Timezone
The Method Getdispatchertype() Is Undefined for the Type Httpservletrequest