【十六】Java 操作cookie
程序员文章站
2022-03-15 10:14:21
...
cookie的读、写、删
package com.sid.util;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
/**
* @program:
* @description: 操作cookie
* @author: Sid
* @date: 2018-11-01 18:15
* @since: 1.0
**/
public class Cookie {
/**
* @Description: 写cookie
* @Param: [key, value, comment, maxAge]
* @return: void
* @Author: Sid
* @Date: 2018-10-23 17:33
* @since: 1.0
*/
public static void set(String key, String value, String comment, int maxAge){
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
// 创建Cookie对象
javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(key, value);
// 配置Cookie对象
cookie.setComment(comment); // Cookie描述
cookie.setMaxAge(maxAge); // Cookie有效时间
cookie.setPath("/"); // Cookie有效路径
cookie.setHttpOnly(true); //http only
// 通过response对象将Cookie写入浏览器,需要解决中文乱码问题,否则会抛出异常
// java.lang.IllegalArgumentException: Control character in cookie value, consider BASE64 encoding your value
response.setCharacterEncoding("UTF-8");
//response.setContentType("text/html;charset=UTF-8");
response.addCookie(cookie);
}
/**
* @Description: 读Cookie
* @Param: [name]
* @return: javax.servlet.http.Cookie
* @Author: Sid
* @Date: 2018-10-23 17:33
* @since: 1.0
*/
public static javax.servlet.http.Cookie get(String name){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
Map<String, javax.servlet.http.Cookie> cookieMap = new HashMap<>();
javax.servlet.http.Cookie[] cookies = request.getCookies();
if (null != cookies) {
for (javax.servlet.http.Cookie cookie : cookies) {
cookieMap.put(cookie.getName(), cookie);
}
}
if (cookieMap.containsKey(name)) {
javax.servlet.http.Cookie cookie = cookieMap.get(name);
return cookie;
} else {
return null;
}
}
/**
* @Description: 删除 当前请求中的 cookie
* @Param: [cookieName]
* @return: void
* @Author: Sid
* @Date: 2018-10-23 17:33
* @since: 1.0
*/
public static void delete(String cookieName){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
// 获取Cookies数组
javax.servlet.http.Cookie[] cookies = request.getCookies();
if(cookies!=null){
// 迭代查找并清除Cookie
for (javax.servlet.http.Cookie cookie: cookies) {
if (cookieName.equals(cookie.getName())) {
cookie.setMaxAge(0);
cookie.setPath("/"); // Cookie有效路径
response.addCookie(cookie);
}
}
}
}
}