在Java中设置cookie的方法有以下几种:
- 使用HttpServletResponse对象的addCookie()方法:
Cookie cookie = new Cookie("cookieName", "cookieValue"); response.addCookie(cookie);
- 使用Cookie对象的setMaxAge()方法设置cookie的有效期:
Cookie cookie = new Cookie("cookieName", "cookieValue"); cookie.setMaxAge(60 * 60); // 设置cookie的有效期为1小时 response.addCookie(cookie);
- 设置cookie的路径和域:
Cookie cookie = new Cookie("cookieName", "cookieValue"); cookie.setPath("/path"); // 设置cookie的路径 cookie.setDomain("example.com"); // 设置cookie的域 response.addCookie(cookie);
- 设置cookie的安全属性:
Cookie cookie = new Cookie("cookieName", "cookieValue"); cookie.setSecure(true); // 设置cookie为安全cookie response.addCookie(cookie);
- 设置cookie的HttpOnly属性:
Cookie cookie = new Cookie("cookieName", "cookieValue"); cookie.setHttpOnly(true); // 设置cookie为HttpOnly cookie response.addCookie(cookie);