2024-06-24 14:48:38 +08:00

139 lines
3.7 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.ruoyi.common.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Cookie工具类
*
* @author ruoyi
*/
public class CookieUtils
{
/**
* 设置 Cookie生成时间为1天
*
* @param name 名称
* @param value 值
*/
public static void setCookie(HttpServletResponse response, String name, String value)
{
setCookie(response, name, value, 60 * 60 * 24);
}
/**
* 设置 Cookie
*
* @param name 名称
* @param value 值
* @param maxAge 生存时间(单位秒)
* @param uri 路径
*/
public static void setCookie(HttpServletResponse response, String name, String value, String path)
{
setCookie(response, name, value, path, 60 * 60 * 24);
}
/**
* 设置 Cookie
*
* @param name 名称
* @param value 值
* @param maxAge 生存时间(单位秒)
* @param uri 路径
*/
public static void setCookie(HttpServletResponse response, String name, String value, int maxAge)
{
setCookie(response, name, value, "/", maxAge);
}
/**
* 设置 Cookie
*
* @param name 名称
* @param value 值
* @param maxAge 生存时间(单位秒)
* @param uri 路径
*/
public static void setCookie(HttpServletResponse response, String name, String value, String path, int maxAge)
{
Cookie cookie = new Cookie(name, null);
cookie.setPath(path);
cookie.setMaxAge(maxAge);
try
{
cookie.setValue(URLEncoder.encode(value, "utf-8"));
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
response.addCookie(cookie);
}
/**
* 获得指定Cookie的值
*
* @param name 名称
* @return 值
*/
public static String getCookie(HttpServletRequest request, String name)
{
return getCookie(request, null, name, false);
}
/**
* 获得指定Cookie的值并删除。
*
* @param name 名称
* @return 值
*/
public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name)
{
return getCookie(request, response, name, true);
}
/**
* 获得指定Cookie的值
*
* @param request 请求对象
* @param response 响应对象
* @param name 名字
* @param isRemove 是否移除
* @return 值
*/
public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name,
boolean isRemove)
{
String value = null;
Cookie[] cookies = request.getCookies();
if (cookies != null)
{
for (Cookie cookie : cookies)
{
if (cookie.getName().equals(name))
{
try
{
value = URLDecoder.decode(cookie.getValue(), "utf-8");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
if (isRemove)
{
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
}
}
return value;
}
}