The Servlet API doesn’t provide a direct way to delete a cookie in a Servlet application. If you want to delete a cookie you have to create a cookie that have the same name with the cookie that you want to delete and set the value to an empty string. You also need to set the max age of the cookie to 0
. And then add this cookie to the servlet’s response object.
Let’s see the code example below:
package org.kodejava.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "DeleteCookieServlet", urlPatterns = "/deleteCookie")
public class DeleteCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//
// To delete a cookie, we need to create a cookie that have the same
// name with the cookie that we want to delete. We also need to set
// the max age of the cookie to 0 and then add it to the Servlet's
// response method.
//
Cookie cookie = new Cookie("username", "");
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
Maven dependencies
<!--https://search.maven.org/remotecontent?filepath=javax/servlet/javax.servlet-api/4.0.1/javax.servlet-api-4.0.1.jar-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
Latest posts by Wayan (see all)
- How do I split large excel file into multiple smaller files? - April 15, 2023
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023