com.tmsps.ne4spring.utils.CookieUtil Maven / Gradle / Ivy
package com.tmsps.ne4spring.utils;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
/**
* @author zhangwei [email protected] CookieUtil
*/
public class CookieUtil {
private CookieUtil() {
}
/**
* 1、name 必需。规定cookie的名称。
* 2、value 必需。规定cookie的值。
* 3、expire 可选。规定cookie的有效时间 <0:关闭浏览器失效;>0:失效的秒数
* 4、path 可选。规定cookie的服务器路径,浏览器在发送cookie时只会发送对应路径及祖先路径的cookie如cookieA设置在根下(path:/),cookieB设置在/dir/下,访问dir的请求会带着cookieB和cookieA,但访问根路径的请求只会带着cookieA
* 5、domain 可选。规定cookie的域名。只能设置为当前域或当前域的上级域。例如,一个在a.b.com的页面,可以设置为a.b.com或.b.com 。如果设置为.b.com的话,那么在其它子域中也能访问到。
* 6、secure 可选。规定是否通过安全的HTTPS连接来传输cookie。如果值为true,则cookie只能在https连接上有效,默认值表示cookie在http和https连接上都有效
* 7、httponly 设置成true,cookie仅通过http协议访问。意思就是cookie无法通过类似JavaScript这样的脚本语言访问。要有效的减少xss攻击时的身份窃取行为,可建议用此设置(虽然不是所有浏览器都支持),不过这个说法经常有争议。
*/
public static void setCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds, String path, String domain, Boolean secure, Boolean isHttpOnly) {
Cookie cookie = new Cookie(name, value);
cookie.setMaxAge(maxAgeInSeconds);
if (path == null) {
path = "/";
}
cookie.setPath(path);
if (domain != null) {
cookie.setDomain(domain);
}
if (isHttpOnly != null) {
cookie.setHttpOnly(isHttpOnly);
}else {
cookie.setHttpOnly(true);
}
if(secure != null) {
cookie.setSecure(secure);
}else {
cookie.setSecure(false);
}
response.addCookie(cookie);
}
// get cookie
public static Cookie getCookieObject(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
return cookie;
}
}
}
return null;
}
public static String getCookie(HttpServletRequest request, String name) {
Cookie cookie = getCookieObject(request, name);
return cookie != null ? cookie.getValue() : "";
}
public static void setCookie(HttpServletResponse response, String name, String value, boolean secure,int maxAgeInSeconds) {
setCookie(response, name, value, maxAgeInSeconds, null, null, secure, null);
}
public static void setCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds) {
setCookie(response, name, value, maxAgeInSeconds, null, null,false, null);
}
}