Cookie

Cookie

什么是 Cookie?

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

如何创建 Cookie

在这里插入图片描述

servlet:

protected void createCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.创建cookie对象
        Cookie cookie = new Cookie("key1", "value1");
        //2.通知客户端保存cookie
        response.addCookie(cookie);
        response.getWriter().write("cookie创建成功!");
    }

服务器如何获取 Cookie

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

在这里插入图片描述

public class CookieUtils {
    /**
     * 查找指定名称的Cookie 对象
     *
     * @param name
     * @param cookies
     * @return
     */
    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 request, HttpServletResponse response) throws ServletException, IOException {

        Cookie cookie = CookieUtils.findCookie("key1", request.getCookies());
        response.getWriter().write("Cookie[key:"+cookie.getName()+" value:"+cookie.getValue()+"]<br>");
    }

Cookie值的修改

方案一

  1. 先创建一个要修改的同名(指的就是 key)的 Cookie 对象
  2. 在构造器,同时赋于新的 Cookie 值。
  3. 调用 response.addCookie( Cookie );
Cookie cookie = new Cookie("key1","newValue1");
resp.addCookie(cookie);

方案二

  1. 先查找到需要修改的 Cookie 对象
  2. 调用 setValue()方法赋于新的 Cookie 值。
  3. 调用 response.addCookie()通知客户端保存修改
Cookie cookie = CookieUtils.findCookie("key2", req.getCookies());
if (cookie != null) 
	cookie.setValue("newValue2");
resp.addCookie(cookie);

Cookie生命控制

Cookie 的生命控制指的是如何管理 Cookie 什么时候被销毁(删除)

setMaxAge()

正数,表示在指定的秒数后过期

负数,表示浏览器一关,Cookie 就会被删除(默认值是-1)

零,表示马上删除 Cookie

protected void createCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.创建cookie对象
        Cookie cookie = new Cookie("key1", "value1");
        //2.通知客户端保存cookie
        response.addCookie(cookie);
        response.getWriter().write("cookie创建成功!");
    }

    protected void getCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Cookie cookie = CookieUtils.findCookie("key1", request.getCookies());
        response.getWriter().write("Cookie[key:"+cookie.getName()+" value:"+cookie.getValue()+"]<br>");
    }

    protected void updateCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie = new Cookie("key1","newValue1");
        response.addCookie(cookie);
    }

    protected void defaultLife(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie = new Cookie("defaultLife", "defaultLife");
        cookie.setMaxAge(-1);
        response.addCookie(cookie);
    }

    protected void deleteNow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //找到要删除的cookie
        Cookie cookie = CookieUtils.findCookie("key1", request.getCookies());
        if(cookie!=null){
            //调用setMaxage
            cookie.setMaxAge(0);
            //addCookie
            response.addCookie(cookie);
        }
    }

    protected void life3600(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie = new Cookie("life3600", "life3600");
        //设置一小时
        cookie.setMaxAge(3600);
        response.addCookie(cookie);
        response.getWriter().write("创建了一个一小时的cookie");
    }

Cookie有效路径 Path 的设置

Cookie 的 path 属性可以有效的过滤哪些 Cookie 可以发送给服务器。哪些不发。path 属性是通过请求的地址来进行有效的过滤。

请求地址如下:

http://ip:port/工程路径/a.html

  • CookieA 发送
  • CookieB 不发送

http://ip:port/工程路径/abc/a.html

  • CookieA 发送
  • CookieB 发送
protected void testPath(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie = new Cookie("path1", "path1");
        // getContextPath() ===>>>> 得到工程路径
        cookie.setPath( request.getContextPath() + "/abc" ); // ===>>>> /工程路径/abc
        response.addCookie(cookie);
        response.getWriter().write("创建了一个带有 Path 路径的 Cookie");
    }

Cookie练习—免输入用户名登录

在这里插入图片描述

login.jsp

<form action="http://localhost:8080/06_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>

LoginServlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if ("admin".equals(username) && "admin".equals(password)) {
            //登录成功
            //当前Cookie 一周内有效resp.addCookie(cookie);
            Cookie cookie = new Cookie("username", username);
            cookie.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(cookie);
            System.out.println("登录 成功");
        } else {
            //登录失败
            System.out.println("登录 失败");
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值