Adding, deleting, modifying and querying cookies in Java

Adding, deleting, modifying and querying cookies in Java

Cookie attribute

Name: the name of the cookie

Value: the value of the cookie

maxAge: the expiration time of the cookie, which is - 1 by default

value Explain
negative Fail immediately after browser is closed
0 Clear cookie s now
Positive number Set expiration time in s econds

path

The effective path of the cookie, / indicates that the path means that the cookie can be accessed under the project. If the path is not set, only the cookie path and its child path can be accessed.

Get all cookies

public static Cookie[] GetCookies(HttpServletRequest request){
    return request.getCookies();
}

It's easy to get cookie s, just get them from the request.

Get the specified Cookie by name

public static Cookie getCookieByName(HttpServletRequest request, String name) {
    if (StringUtils.isBlank(name)) {
        return null;
    }
    Cookie[] cookies = getCookies(request);
    if (null != cookies) {
        for (Cookie cookie : cookies) {
            if (name.equals(cookie.getName())) {
                return cookie;
            }
        }
    }
    return null;
}

Add Cookie

public static boolean addCookie(HttpServletResponse response, String name, String value,
            int maxAge) {
    if (StringUtils.isBlank(name) || StringUtils.isBlank(value)) {
        return false;
    }
    Cookie cookie = new Cookie(name.trim(), value.trim());
    if (maxAge <= 0) {
        maxAge = Integer.MAX_VALUE;
    }
    cookie.setMaxAge(maxAge);
    cookie.setPath("/");
    response.addCookie(cookie);
    return true;
}

Delete Cookie

public static boolean removeCookie(HttpServletRequest request, HttpServletResponse response,
            String name) {
    if (StringUtils.isBlank(name)) {
        return false;
    }
    Cookie[] cookies = getCookies(request);
    if (null != cookies) {
        for (Cookie cookie : cookies) {
            if (name.equals(cookie.getName())) {
                cookie.setValue(null);
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
                return true;
            }
        }
    }
    return false;
}

Tips

Editing operation is the same as deleting operation, but it should be noted that when modifying or deleting cookies, all attributes except value and maxAge, such as name, path, domain, etc., should be exactly the same as the original Cookie. Otherwise, the browser will be regarded as two different cookies not to be overwritten, resulting in modification and deletion failure.

Tags: Windows Java Attribute

Posted on Mon, 04 Nov 2019 10:18:26 -0500 by dalecosp