Cookie和Sesstion --JavaWeb

1、Cookie

a)什么是Cookie?

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

b)如何创建Cookie

在这里插入图片描述

package demo01;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

public class CreateCookie extends BaseServlet{
    protected void createCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie1 = new Cookie("key01", "value01");
        Cookie cookie2 = new Cookie("key02", "value02");
        response.addCookie(cookie1);
        response.addCookie(cookie2);
        response.getWriter().write("cookie创建成功");
    }
}

c)服务器如何获取Cookie

服务器获取客户端的Cookie 只需要一行代码:req.getCookies():Cookie[]
在这里插入图片描述
getCookie类:

protected void getCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            response.getWriter().write("Cookie = " + "{" + cookie.getName() + "," + cookie.getValue() + "}\n");
        }
        Cookie want_cookie=null;
        for (Cookie cookie : cookies) {
            String s = cookie.getName();
            if("key01".equals(s)){
                want_cookie = cookie;break;
            }
        }
        if(want_cookie!=null){
            response.getWriter().write("找到了你要的cookie");
        }
    }

d)Cookie 值的修改

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

protected void updateCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("123333333333");
        Cookie cookie = new Cookie("key01", "newvalue101");
        response.addCookie(cookie);
        response.getWriter().write("已经修改完成!!!");
    }

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

protected void updateCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        Cookie want_cookie = null;
        for (Cookie cookie : cookies) {
            String s = cookie.getName();
            if ("key02".equals(s)) {
                want_cookie = cookie;
                break;
            }
        }
        if (want_cookie != null) {
// 2、调用setValue()方法赋于新的Cookie 值。
            want_cookie.setValue("newValue2");
// 3、调用response.addCookie()通知客户端保存修改
            response.addCookie(want_cookie);
        }
    }

注意:在创建 cookie 之后将新值分配给 cookie。如果使用二进制值,则可能需要使用 BASE64 编码。
对于 Version 0 cookie,值不应包含空格、方括号、圆括号、等号、逗号、双引号、斜杠、问号、at 符号、冒号和分号。空值在所有浏览器上的行为不一定相同。

e)浏览器查看Cookie:

谷歌浏览器如何查看Cookie:
在这里插入图片描述

f) Cookie 生命控制

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

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

    protected void life3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        Cookie cookie = new Cookie("life3600", "life3600");
        cookie.setMaxAge(60 * 60); // 设置Cookie 一小时之后被删除。无效
        resp.addCookie(cookie);
        resp.getWriter().write("已经创建了一个存活一小时的Cookie");
    }

    protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
// 先找到你要删除的Cookie 对象
        Cookie cookie = CookieUtils.findCookie("key4", req.getCookies());
        if (cookie != null) {
// 调用setMaxAge(0);
            cookie.setMaxAge(0); // 表示马上删除,都不需要等待浏览器关闭
// 调用response.addCookie(cookie);
            resp.addCookie(cookie);
            resp.getWriter().write("key4 的Cookie 已经被删除");
        }
    }

g)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");
// getContextPath() ===>>>> 得到工程路径
        cookie.setPath( req.getContextPath() + "/abc" ); // ===>>>> /工程路径/abc
        resp.addCookie(cookie);
        resp.getWriter().write("创建了一个带有Path 路径的Cookie");
    }

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

在这里插入图片描述

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>$Title$</title>
</head>
<body>
<form action="http://localhost:8080/login" method="post">
    用户名:<input type="text" name="username" value="${cookie.username.value}">
    密码:<input type="password" name="password">
    <input type="submit" value="登录i">
</form>
</body>
</html>

LoginServlet.java

package demo01;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username.equals("hyh")&&password.equals("123")){
            Cookie cookie = new Cookie("username", username);
            cookie.setMaxAge(60 * 60 * 24 * 7);
            resp.addCookie(cookie);
            System.out.println("登陆成功");
        }
        else{
            System.out.println("登录失败");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

2、Session 会话

Cookie通过在客户端记录信息确定用户身份;
Session通过在服务器端记录信息确定用户身份;

i) 什么是Session 会话?

1、Session 就一个接口(HttpSession)。
2、Session 就是会话。它是用来维护一个客户端和服务器之间关联的一种技术。
3、每个客户端都有自己的一个Session 会话。
4、Session 会话中,我们经常用来保存用户登录之后的信息。

j) 如何创建Session 和获取(id 号,是否为新)

如何创建和获取Session。它们的API 是一样的。

  • request.getSession()
    第一次调用是:创建Session 会话
    之后调用都是:获取前面创建好的Session 会话对象。
  • isNew(); 判断到底是不是刚创建出来的(新的)
    true 表示刚创建
    false 表示获取之前创建

每个会话都有一个身份证号。也就是ID 值。而且这个ID 是唯一的。
getId() 得到Session 的会话id 值。

k)Session 域数据的存取

protected void getAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object key01 = request.getSession().getAttribute("key01");
        response.getWriter().write("get: "+key01 +"<br>");
    }
    protected void setAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().setAttribute("key01", "value01");
        response.getWriter().write("已经保存成功数据<br>");
    }

l) Session 生命周期控制

  • public void setMaxInactiveInterval(int interval)
    • 设置Session 的超时时间(以秒为单位),超过指定的时长,Session
      就会被销毁。
      • 值为正数的时候,设定Session 的超时时长。
      • 负数表示永不超时(极少使用)
  • public int getMaxInactiveInterval()获取Session 的超时时间
  • public void invalidate() 让当前Session 会话马上超时无效。

Session 默认的超时时长是多少!
Session 默认的超时时间长为30 分钟。
因为在Tomcat 服务器的配置文件web.xml 中默认有以下的配置,它就表示配置了当前Tomcat 服务器下所有的Session
超时配置默认时长为:30 分钟。

<session-config>
    <session-timeout>30</session-timeout>
  </session-config>

如果说。你希望你的web 工程,默认的Session 的超时时长为其他时长。你可以在你自己的web.xml 配置文件中做
以上相同的配置。就可以修改你的web 工程所有Seession 的默认超时时长。

<session-config>
    <session-timeout>20</session-timeout>
  </session-config>
  • 如果你想只修改个别Session 的超时时长。就可以使用上面的API。setMaxInactiveInterval(int interval)来进行单独的设
    置。
    • session.setMaxInactiveInterval(int interval)单独设置超时时长。

示例代码:

protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 先获取Session 对象
        HttpSession session = req.getSession();
        // 设置当前Session3 秒后超时
        session.setMaxInactiveInterval(3);
        resp.getWriter().write("当前Session 已经设置为3 秒后超时");
    }
protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 先获取Session 对象
        HttpSession session = req.getSession();
        // 让Session 会话马上超时
        session.invalidate();
        resp.getWriter().write("Session 已经设置为超时(无效)");
    }

Session 超时的概念介绍:
在这里插入图片描述

m) 浏览器和Session 之间关联的技术内幕

Session 技术,底层其实是基于Cookie 技术来实现的。
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值