Remove a cookie by name and its default path "/" from Servlet. - Java Servlet JSP

Java examples for Servlet JSP:Servlet

Description

Remove a cookie by name and its default path "/" from Servlet.

Demo Code


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Main{
    /**//from www. j a  va  2s  .  co  m
     * Remove a cookie by name and its default path "/".
     * 
     * @param name Cookie name.
     */
    public static void removeCookie(String name) {
        setCookie(name, "__deleted__", 0, "/");
    }
    /**
     * Remove a cookie by name and its path.
     * 
     * @param name Cookie name.
     * @param path Cookie path.
     */
    public static void removeCookie(String name, String path) {
        setCookie(name, "__deleted__", 0, path);
    }
    /**
     * Set new cookie by name, value and max age, with default path "/".
     * 
     * @param name Cookie name.
     * @param value Cookie value.
     * @param maxAgeInSeconds Cookie age in seconds.
     */
    public static void setCookie(String name, String value,
            int maxAgeInSeconds) {
        setCookie(name, value, maxAgeInSeconds, "/");
    }
    /**
     * Set new cookie by name, value, max age and path.
     * 
     * @param name Cookie name.
     * @param value Cookie value.
     * @param maxAgeInSeconds Cookie age in seconds.
     * @param path Cookie path.
     */
    public static void setCookie(String name, String value,
            int maxAgeInSeconds, String path) {
        HttpServletResponse response = ActionContext.getActionContext()
                .getHttpServletResponse();
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAgeInSeconds);
        cookie.setPath(path);
        response.addCookie(cookie);
    }
}

Related Tutorials