封装Cookie API

本文详细介绍了Cookie的工作原理,如何设置生命周期、路径和域,以及如何实现跨域数据共享。重点讲解了CookieUtil工具API的使用,包括添加、删除和获取Cookie的方法。涵盖了Cookie的常见操作和权限控制。
摘要由CSDN通过智能技术生成

Cookie: 在客户端保存服务器数据,在客户端实现数据共享.
* cookie.setMaxAge(); cookie生命周期
* cookie.setMaxAge(0); 立即删除cookie
* cookie.setMaxAge(100); 设定100秒有效期 100秒之后自动删除
* cookie.setMaxAge(-1); 关闭会话后删除
设定path cookie的权限设定
* cookie.setPath(“/”) 一般条件下设定为/ 通用
* 权限:根目录及其子目录有效
* cookie.setPath(“/user”)
* 权限:/user目录下有效
设定Cookie资源共享
* cookie特点: 自己的域名下,只能看到自己的Cookie. 默认条件下不能共享的
* cookie.setDomain(“jt.com”); 只有在xxx.jt.com的域名中实现数据共享

package com.xxx.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//工具API 主要负责 新增cookie 删除cookie  根据key获取cookie  获取cookie的值
public class CookieUtil {

    public static void addCookie(HttpServletResponse response,String name, String value, int maxAge, String path, String domain){
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        cookie.setPath(path);
        cookie.setDomain(domain);
        response.addCookie(cookie);
    }

    public static void delCookie(HttpServletResponse response,String name,String path, String domain){

        addCookie(response, name, "", 0, path, domain);
    }

    public static Cookie getCookie(HttpServletRequest request,String name){
        Cookie[] cookies = request.getCookies();
        if(cookies !=null && cookies.length >0){
            for (Cookie cookie : cookies){
                if(name.equals(cookie.getName())){

                    return cookie;
                }
            }
        }
        return null;
    }

    public static String getCookieValue(HttpServletRequest request,String name){
        Cookie cookie = getCookie(request, name);
        return cookie==null?null:cookie.getValue();
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值