In a Java Servlet how can I change the value of an existing cookie? There is an addCookie method, but no deleteCookie or editCookie in HttpServletResponse
Those indeed don't exist. Just create utility methods yourself which do that. Particularly getting the desired cookie is quite bloated. E.g.
public final class Servlets {
private Servlets() {}
public static Cookie getCookie(HttpServletRequest request, String name) {
if (request.getCookies() != null) {
for (Cookie cookie : request.getCookies()) {
if (cookie.getName().equals(name)) {
return cookie;
}
}
}
return null;
}
}
To edit a cookie, set its value and then add it to the response:
Cookie cookie = Servlets.getCookie(request, "foo");
if (cookie != null) {
cookie.setValue(newValue);
response.addCookie(cookie);
}
Set if necessary the maxage, path and domain as well if they differs from your default. The client namely doesn't send this information back.
To delete a cookie, set the max age to 0
(and preferably also the value to null
):
Cookie cookie = Servlets.getCookie(request, "foo");
if (cookie != null) {
cookie.setMaxAge(0);
cookie.setValue(null);
response.addCookie(cookie);
}
Set if necessary the path and domain as well if they differs from your default. The client namely doesn't send this information back.
Here is an example from kodejava:
public class ReadCookieExample extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
writer.println("Name: " + cookies[i].getName() + "; Value: " + cookies[i].getValue());
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
That will get the cookies list, get the one you want and instead of printing out values, do something similar to this:
cookie.setValue(String.valueOf(<new Value>));
cookie.setMaxAge(60*60*24*365);
cookie.setPath("/");
response.addCookie(cookie); etc...
HTH,
James