直接上代碼犀变,如下
package com.hu.flyCloud.util.cookie;
import org.springframework.util.StringUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookieUtil {
/**
* 在request對象中獲取指定Cookie
*
* @param request request對象
* @param cookieName Cookie名稱
* @return 查找到的Cookie對象
*/
public static Cookie getCookie(HttpServletRequest request, String cookieName) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie != null && cookieName.equals(cookie.getName())) {
return cookie;
}
}
}
return null;
}
/**
* 添加cookie
*
* @param response response
* @param name Cookie名稱
* @param value Cookie值
* @param path Cookie寫入路徑
* @param domain Cookie的作用域
* @param timeout Cookie有效期 (秒)
*/
public static void addCookie(HttpServletResponse response, String name, String value, String path, String domain, int timeout) {
Cookie cookie = new Cookie(name, value);
if (StringUtils.isEmpty(path) == true) {
path = "/";
}
if (StringUtils.isEmpty(domain) == false) {
cookie.setDomain(domain);
}
cookie.setPath(path);
cookie.setMaxAge(timeout);
response.addCookie(cookie);
}
/**
* 刪除Cookie
*
* @param request request對象
* @param response response對象
* @param name Cookie名稱
*/
public static void delCookie(HttpServletRequest request, HttpServletResponse response, String name) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie != null && (name).equals(cookie.getName())) {
addCookie(response, name, null, null, null, 0);
return;
}
}
}
}
/**
* 修改cookie的value值
*
* @param request request對象
* @param response response對象
* @param name Cookie名稱
* @param value Cookie值
*/
public static void updateCookie(HttpServletRequest request, HttpServletResponse response, String name,
String value) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie != null && (name).equals(cookie.getName())) {
addCookie(response, name, value, cookie.getPath(), cookie.getDomain(), cookie.getMaxAge());
return;
}
}
}
}
}