<返回更多

Web-7-深入理解Cookie与Session:实现用户跟踪和数据存储

2023-08-02  今日头条  springboot葵花宝典
加入收藏
HTTP协议是无状态协议,每次同一浏览器向服务器请求时,服务器都会将该请求视为新的请求,因此我们需要会话跟踪技术来实现同一会话内数据共享.

深入理解Cookie与Session:实现用户跟踪和数据存储

今日目标

掌握客户端会话跟踪技术Cookie

掌握服务端会话跟踪技术Sesssion

一、会话跟踪技术介绍

会话:用户打开浏览器,访问web服务器的资源,会话建立,直到有一方断开连接,会话结束。一次会话中可以包含多次请求和响应。

HTTP协议是无状态协议,每次同一浏览器向服务器请求时,服务器都会将该请求视为新的请求,因此我们需要会话跟踪技术来实现同一会话内数据共享

思考:下图建立几个会话?

每个浏览器都会与服务端建立了一个会话,加起来总共是3个会话。

思考:服务器如何识别多次请求是否来自于同一浏览器?这就需要我们学习今天的内容,会话跟踪技术。

会话跟踪:一种维护浏览器状态的方法,服务器需要识别多次请求是否来自于同一浏览器,以便在同一次会话的多次请求间共享数据

原因:HTTP协议是无状态的,每次浏览器向服务器请求时,服务器都会将该请求视为新的请求,因此我们需要会话跟踪技术来实现会话内数据共享

思考:一个会话中的多次请求为什么要共享数据呢?有了这个数据共享功能后能实现哪些功能呢?

购物车功能: 加入购物车和去购物车结算是两次请求,但是后面这次请求要想展示前一次请求所添加的商品,就需要用到数据共享。

记住我功能:当用户登录成功后,勾选记住我按钮后下次再登录的时候,网站就会自动填充用户名和密码,简化用户的登录操作,多次登录就会有多次请求,他们之间也涉及到共享数据

实现方式:

二、Cookie基本使用

Cookie:客户端会话跟踪技术,将数据保存到客户端,以后每次请求都携带Cookie数据进行访问

1、基本使用

(1)发送Cookie

Cookie cookie = new Cookie("key","value");
response.addCookie(cookie);

(2)获取Cookie

Cookie[] cookies = request.getCookies();
cookie.getName();
cookie.getValue();

2、代码实现

<dependencies>
    <dependency>
      <groupId>JAVAx.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
 
Cookie[] cookies = request.getCookies();
 
package com.zbbmeta.cookie;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
/**
 * 发送Cookie
 */
@WebServlet(value = "/a")
public class Aservlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //get请求
        //1.创建cookie对象
        Cookie cookie = new Cookie("name","lisi");

        //2.发送cookie对象到浏览器
        response.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //post请求
        doGet(request, response);
    }
}
package com.zbbmeta.cookie;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 获取Cookie
 */
@WebServlet(value = "/b")
public class Bservlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //get请求
        //3.获取客户端携带的所有Cookie,使用request对象
        Cookie[] cookies = request.getCookies();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        if(cookies!=null){
            //4.遍历数组,获取每一个Cookie对象:for
            for (Cookie cookie : cookies) {
                //5.使用Cookie对象方法获取数据
                String name = cookie.getName();
                String value = cookie.getValue();
                writer.write(name+" = "+value+"<br>");
            }
        }else {

            writer.write("cookie不存在<br>");
        }

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //post请求
        doGet(request, response);
    }
}

三、Cookie原理

Cookie的实现是基于HTTP协议的。

在浏览器 查看Cookie。

1、Cookie使用细节 3.1Cookie 存活时间

package com.zbbmeta.cookie;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
/**
 * 发送Cookie
 */
@WebServlet(value = "/a")
public class Aservlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //get请求
        //1.创建cookie对象
        Cookie cookie = new Cookie("name","lisi");
        //3. setMaxAge(int seconds):设置Cookie存活时间,但是是秒
        cookie.setMaxAge(10);
//        cookie.setMaxAge(-1);
        //cookie.setMaxAge(0);
        //2.发送cookie对象到浏览器
        response.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //post请求
        doGet(request, response);
    }
}
 

2、Cookie 存储问题

在发送cookie端进行URL编码。

URLEncoder.encode(name,"UTF-8");

在获取cookie端进行URL解码。

value = URLDecoder.decode(name,"UTF-8");

浏览器显示结果。

package com.zbbmeta.cookie;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.NET.URLDecoder;
import java.net.URLEncoder;

/**
 * 发送Cookie
 */
@WebServlet(value = "/a")
public class Aservlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //get请求
        //1.创建cookie对象
        String name = " lisi";
        name = URLEncoder.encode(name,"UTF-8");
        Cookie cookie = new Cookie("name",name);
        //3. setMaxAge(int seconds):设置Cookie存活时间,但是是秒
        cookie.setMaxAge(10);
//        cookie.setMaxAge(-1);
        //cookie.setMaxAge(0);
        //2.发送cookie对象到浏览器
        response.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //post请求
        doGet(request, response);
    }
}
 
package com.zbbmeta.cookie;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

/**
 * 获取Cookie
 */
@WebServlet(value = "/b")
public class Bservlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //get请求
        //3.获取客户端携带的所有Cookie,使用request对象
        Cookie[] cookies = request.getCookies();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        if(cookies!=null){
            //4.遍历数组,获取每一个Cookie对象:for
            for (Cookie cookie : cookies) {
                //5.使用Cookie对象方法获取数据
                String name = cookie.getName();
                String value = cookie.getValue();
                value = URLDecoder.decode(value,"UTF-8");
                writer.write(name+" = |"+value+"<br>");
            }
        }else {

            writer.write("cookie不存在<br>");
        }

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //post请求
        doGet(request, response);
    }
}

四、Session基本使用

Session:服务端会话跟踪技术:将数据保存到服务端

1、基本使用

(1)获取Session

HttpSession session = request.getSession();

(2)Session对象功能
void setAttribute(String name, Object o)//存储数据到 session 域中
   Object getAttribute(String name) //根据 key,获取值
   void removeAttribute(String name) //根据 key,删除该键值对

2、代码实现

package com.zbbmeta.session;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 1.存储Session数据到服务器
 */
@WebServlet(value = "/c")
public class CServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //get请求
        //1.获取Session对象
        HttpSession session = request.getSession();
        //2.存储数据到session
        session.setAttribute("name","session_wangwu");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();

        writer.write("访问了C资源"+"<br>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //post请求
        doGet(request, response);
    }
}
 
package com.zbbmeta.session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 2.在Session对象中获取数据
 */
@WebServlet(value = "/d")
public class DServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //get请求
        //1.获取Session对象
        HttpSession session = request.getSession();
        //2.存储数据到session
        Object name = session.getAttribute("name");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("访问了D资源"+"<br>");
        if(name!=null){
            writer.write(name.toString()+"<br>");
        }else {
            writer.write("Session数据不存在"+"<br>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //post请求
        doGet(request, response);
    }
}

五、Session原理

Session基于Cookie实现

思考:如果新开一个浏览器,还是同一个session对象么?

答案:上图显示的获取的Session对象不是一个,每一个浏览器都会获取一个新的Session对象。

package com.zbbmeta.session;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 1.存储Session数据到服务器
 */
@WebServlet(value = "/c")
public class CServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //get请求
        response.setContentType("text/html;charset=utf-8");

        PrintWriter writer = response.getWriter();
        //1.获取Session对象
        HttpSession session = request.getSession();

        //3.判断Session是否是新对象
        boolean aNew = session.isNew();
        //4.获取SessionID
        String id = session.getId();
        writer.write("session 是新的= "+aNew+" session id : "+id+"<br>");

        //2.存储数据到session
        session.setAttribute("name","session_wangwu");


        writer.write("访问了C资源"+"<br>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //post请求
        doGet(request, response);
    }
}
 
package com.zbbmeta.session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 2.在Session对象中获取数据
 */
@WebServlet(value = "/d")
public class DServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //get请求
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        //1.获取Session对象
        HttpSession session = request.getSession();
        //3.判断Session是否是新对象
        boolean aNew = session.isNew();
        //4.获取SessionID
        String id = session.getId();
        writer.write("session 是新的= "+aNew+" session id : "+id+"<br>");

        //2.存储数据到session
        Object name = session.getAttribute("name");

        writer.write("访问了D资源"+"<br>");
        if(name!=null){
            writer.write(name.toString()+"<br>");
        }else {
            writer.write("Session数据不存在"+"<br>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //post请求
        doGet(request, response);
    }
}

六、Session使用细节

1、Session 钝化、活化

在IDEA中配置钝化

查看钝化数据

查看钝化数据的前台条件是,我们已经有Session对象存储数据。

2、Seesion 销毁

(1)默认情况下,无操作,30分钟自动销毁

//5.获取存活时间
        int maxInactiveInterval = session.getMaxInactiveInterval();

思考:为什么停留10s后,session对象的存活时间还是1800s?

存活时间表示的是没有访问资源的情况下,如果访问了,则存活时间重新变为1800s.

(2)web.xml配置存活时间

可以通过web.xml进行配置,单位为分钟。

<?xml versinotallow="1.0" encoding="UTF-8"?>
<web-App xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 version="4.0">

 <session-config>
<!--  单位是分钟-->
  <session-timeout>2</session-timeout>
 </session-config>
</web-app>

注意:最好关闭浏览器再打开。

3、Cookie和Session的对比

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>