cookie的操作

1. 将cookie返回给浏览器

// 创建一个cookie
Cookie cookie = new Cookie("cookieName", "cookieInfo");
// 设置只有浏览器可读
cookie.setHttpOnly(true);
// 设置保留时长 -1为不删除
cookie.setMaxAge(-1);
// 设置cookie保留的路径
cookie.setPath("/");
response.addCookie(cookie);

2. 获取cookie

private String getToken(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null || cookies.length == 0) {
         return null;
    }
    for (Cookie cookie : cookies) {
        if ("cookieName".equals(cookie.getName())) {
            return cookie.getValue();
        }
    }
    return null;
}

 

你可能感兴趣的:(java)