CookieUtil

 

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

public class CookieUtil

{

  private static final Logger LOGGER = LoggerFactory.getLogger(CookieUtil.class);

 

  public static void writeCookie(HttpServletResponse response, String key, String value)

  {

    writeCookie(response, key, value, 2592000, "/");

  }

 

  public static void writeCookie(HttpServletResponse response, String key, String value, int maxAge, String path)

  {

    try

    {

      Cookie cookie = new Cookie(key, value);

 

      cookie.setMaxAge(maxAge);

 

      cookie.setPath(path);

      response.addCookie(cookie);

    } catch (Exception e) {

      e.printStackTrace();

    }

  }

 

  public static String getCookieValue(HttpServletRequest request, String key)

  {

    Cookie[] cc = request.getCookies();

    if (cc == null)

      return null;

    for (Cookie cookie : cc) {

      if (cookie.getName().equals(key)) {

        return cookie.getValue();

      }

    }

    return null;

  }

 

  public static void removeCookie(String name, HttpServletRequest request, HttpServletResponse response)

  {

    Cookie[] cc = request.getCookies();

    if ((cc == null) || (cc.length < 1))

    {

      LOGGER.error("请求里cookie为null");

    }

    for (Cookie cookie : cc)

      if (cookie.getName().equals(name)) {

        cookie.setMaxAge(0);

        cookie.setPath("/");

        response.addCookie(cookie);

      }

  }

}

转载于:https://www.cnblogs.com/chinaifae/p/10408018.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值