20 Cookie

一、Cookie 饼干

1、Cookie 翻译过来是饼干的意思。
2、Cookie 是服务器通知客户端保存键值对的一种技术。
3、客户端有了 Cookie 后,每次请求都发送给服务器。
4、每个 Cookie 的大小不能超过 4kb

Servlet 程序中的代码:

    protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.创建cookie对象
        Cookie cookie = new Cookie("key1", "Value1");
        //2.通知客户端保存cookie
        resp.addCookie(cookie);

        Cookie cookie2 = new Cookie("key2", "Value2");
        resp.addCookie(cookie2);

        resp.getWriter().write("cookie创建成功");
        
    }

服务器获取客户端的 Cookie 只需要一行代码:req.getCookies():Cookie[]

Cookie 的工具类:

public class CookieUtils {

    public static Cookie findCookie(String name,Cookie[] cookies){
        if (name == null || cookies==null || cookies.length == 0){
            return null;
        }

        for (Cookie cookie : cookies) {
            if (name.equals(cookie.getName())){
                return cookie;
            }
        }
        return null;
    }
}

Servlet 程序中的代码:

    protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();

        for (Cookie cookie : cookies) {
            //getName()方法返回cookie的key
//            getValue()方法返回cookie的value
            resp.getWriter().write("cookie[" + cookie.getName() + "" + cookie.getValue() + "]");
        }

        Cookie iWantCookie = CookieUtils.findCookie("key1",cookies);

        if (iWantCookie != null){
            resp.getWriter().write("找到了 ");
        }

    }

d)Cookie 值的修改

方案一:
1、先创建一个要修改的同名(指的就是 key)的 Cookie 对象
2、在构造器,同时赋于新的 Cookie 值。
3、调用 response.addCookie( Cookie );

    protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //1.先创建一个要修改的同名的Cookie对象
            //2.在构造器,同时赋予新的Cookie值
       Cookie cookie = new Cookie("key1","newValue1");

            //3.调用resp.addCookie(cookie);通知客户端保存修改
        resp.addCookie(cookie);

  

    }

方案二:
1、先查找到需要修改的 Cookie 对象
2、调用 setValue()方法赋于新的 Cookie 值。
3、调用 response.addCookie()通知客户端保存修改

 protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {       
		//1.先查找到需要修改的cookie对象
        Cookie cookie = CookieUtils.findCookie("key2",req.getCookies());
        if (cookie != null){
            //2.调用setValue()方法赋予新的Cookie值
            cookie.setValue("newValue2");
        }

        //3.调用resp.addCookie(cookie);通知客户端保存修改
        resp.addCookie(cookie);

    }

Cookie 的生命控制指的是如何管理 Cookie 什么时候被销毁(删除)
setMaxAge()
正数,表示在指定的秒数后过期
负数,表示浏览器一关,Cookie 就会被删除(默认值是-1)
零,表示马上删除 Cooki

    //默认会话级别的Cookie
	protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("default","life");

        cookie.setMaxAge(-1);//设置存活时间

        resp.addCookie(cookie);

    }

	//设置存活1个小时的Cookie
    protected void life360(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("life","life360");
        cookie.setMaxAge(60*60);//设置cookie一小时后被删除
        resp.addCookie(cookie);

    }

	//马上删除Cookie
    protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.先找到你要删除的cookie对象
        Cookie cookie = CookieUtils.findCookie("key1",req.getCookies());
        if (cookie != null){
            //2.调用 cookie.setMaxAge(0)
            cookie.setMaxAge(0);//表示马上删除,不需要等待浏览器关闭
        }
        //3.调用resp.addCookie(cookie);通知客户端保存修改
        resp.addCookie(cookie);
    }

f)Cookie 有效路径 Path 的设置

Cookie 的 path 属性可以有效的过滤哪些 Cookie 可以发送给服务器。哪些不发。
path 属性是通过请求的地址来进行有效的过滤。
CookieA path=/工程路径
CookieB path=/工程路径/abc
请求地址如下:
http://ip:port/工程路径/a.html
CookieA 发送
CookieB 不发送
http://ip:port/工程路径/abc/a.html
CookieA 发送
CookieB 发送

  protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("path1","path1");
        //req.getContextPath() ====? 得到工程路径
        cookie.setPath(req.getContextPath() + "abc");// ===> /工程路径/abc
        resp.addCookie(cookie);
    }

g)Cookie 练习---免输入用户名登录

login.jsp 页面

<body>
<form action="http://localhost:8080/13_cookie_session/loginServlet" method="get">
    用户名:<input type="text" name="username" value="${cookie.username.value}"> <br>
    密码:<input type="password" name="password"> <br>
    <input type="submit" value="登录">
</form>
</body>

LoginServlet 程序

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if ("qwe123".equals(username) && "123456".equals(password)){
            //登录成功
            Cookie cookie = new Cookie("username", username);
            cookie.setMaxAge(60*60*24*7);
            resp.addCookie(cookie);
            System.out.println("登录成功");
        }else{
            //登陆失败
            System.out.println("登陆失败");

        }
    }
posted @   flypiggg  阅读(32)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示