• Session 和 Cookie 使用


    目录

    一、Cookie

    1、Cookie的创建

      2、服务器获取Cookie

    3、Cookie值的修改

    方案一

    方案二

    4、浏览器查看Cookie

    5、Cookie生命控制

     6、Cookie有效路径Path的设置

     7、Cookie免输入用户名登录

    二、Session

    1、Session

    2、创建Session和获取

    3、Session域数据的存取

    4、Session生命周期控制

     5、浏览器和Session之间关联的技术内幕


    一、Cookie

    Cookie  是服务器通知客户端保存键值对的一种技术。客户端有了  Cookie  后,每次请求都发送给服务器。每个  Cookie  的大小不能超过  4kb

    1、Cookie的创建

    使用BaseServlet抽取Servlet对象,在请求中携带名称为action,值为方法名的参数动态调用请求方法。

    1. public abstract class BaseServlet extends HttpServlet{
    2. @Override
    3. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    4. doPost(req,resp);
    5. }
    6. @Override
    7. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    8. //解决请求中文乱码问题
    9. req.setCharacterEncoding("UTF-8");
    10. //解决响应中文乱码问题
    11. resp.setContentType("text/html; charset=UTF-8");
    12. //获取参数action的值
    13. String action=req.getParameter("action");
    14. try {
    15. // 匹配指定名称和参数的类的方法,此方法返回的是Method对象
    16. Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
    17. //调用目标业务方法,这里的 this 是子类
    18. method.invoke(this,req,resp);
    19. } catch (Exception e){
    20. e.printStackTrace();
    21. }
    22. }
    23. }

    Servlet程序 

    1. public class CookieServlet extends BaseServlet {
    2. protected void createCookie(HttpServletRequestreq,HttpServletResponse resp)throwsServletException, IOException {
    3. //1 创建 Cookie对象
    4. Cookie cookie = new Cookie("key4", "value4");
    5. //2 通知客户端保存 Cookie
    6. resp.addCookie(cookie);
    7. resp.getWriter().write("Cookie创建成功");
    8. }
    9. }

    web.xml

    1. <servlet>
    2. <servlet-name>CookieServletservlet-name>
    3. <servlet-class>com.servlet.CookieServletservlet-class>
    4. servlet>
    5. <servlet-mapping>
    6. <servlet-name>CookieServletservlet-name>
    7. <url-pattern>/cookieServleturl-pattern>
    8. servlet-mapping>

    请求地址:localhost:8080/13_cookie_session/cookieServlet?action=createCookie

     解释:当请求到达CookieServlet,由于没有 doGet() 方法,会向父类寻找, BaseServlet中有 doGet()方法,调用父类的 doGet()方法,首先获取 action 的值createCoookie,这里的 this是子类,通过反射调用子类名为 createCookie 的方法。

      2、服务器获取Cookie

     Cookie的工具类:查找指定名称的  Cookie对象

    1. public class CookieUtils {
    2. public static Cookie findCookie(String name,Cookie[] cookies){
    3. if(name==null||cookies==null||cookies.length==0){
    4. return null;
    5. }
    6. for(Cookie cookie : cookies){
    7. if(name.equals(cookie.getName())){
    8. return cookie;
    9. }
    10. }
    11. return null;
    12. }
    13. }
    1. protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    2. Cookie[] cookies = req.getCookies();
    3. for (Cookie cookie : cookies) {
    4. resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "]
      "
      );
    5. }
    6. Cookie iWantCookie = CookieUtils.findCookie("key3", cookies);
    7. if (iWantCookie != null) {
    8. resp.getWriter().write("找到了需要的Cookie");
    9. }
    10. }

    3、Cookie值的修改

    方案一

    1. protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletExcepton, IOException {
    2. Cookie cookie = new Cookie("key3","NewValue");
    3. resp.addCookie(cookie);
    4. }

    方案二

    1. protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    2. Cookie cookie1 = CookieUtils.findCookie("key3", req.getCookies());
    3. if(cookie1!=null){
    4. cookie1.setValue("newValue2");
    5. resp.addCookie(cookie1);
    6. }
    7. }

    4、浏览器查看Cookie

    5、Cookie生命控制

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

    setMaxAge()

    • 正数,表示在指定的秒数后过期
    • 负数,表示浏览器一关,Cookie  就会被删除(默认值是-1) 
    • 零,表示马上删除  Cookie
    1. protected void life3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    2. Cookie cookie = new Cookie("life3600", "life3600");
    3. cookie.setMaxAge(60 * 60);
    4. resp.addCookie(cookie);
    5. resp.getWriter().write("已经创建了一个存活一小时的 Cookie");
    6. }
    7. protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    8. Cookie cookie = CookieUtils.findCookie("key3", req.getCookies());
    9. if(cookie!=null){
    10. cookie.setMaxAge(0);
    11. resp.addCookie(cookie);
    12. resp.getWriter().write("key3已删除");
    13. }
    14. }
    15. protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    16. Cookie cookie = new Cookie("defalutLife","defaultLife");
    17. cookie.setMaxAge(-1);//设置存活时间
    18. resp.addCookie(cookie);
    19. resp.getWriter().write("默认的会话级别的Cookie");
    20. }

    cookie.html

    1. html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    2. <html>
    3. <head>
    4. <meta http-equiv="pragma" content="no-cache" />
    5. <meta http-equiv="cache-control" content="no-cache" />
    6. <meta http-equiv="Expires" content="0" />
    7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    8. <title>Cookietitle>
    9. <base href="http://localhost:8080/13_cookie_session/">
    10. <style type="text/css">
    11. ul li {
    12. list-style: none;
    13. }
    14. style>
    15. head>
    16. <body>
    17. <iframe name="target" width="500" height="500" style="float: left;">iframe>
    18. <div style="float: left;">
    19. <ul>
    20. <li><a href="cookieServlet?action=createCookie" target="target">Cookie的创建a>li>
    21. <li><a href="cookieServlet?action=getCookie" target="target">Cookie的获取a>li>
    22. <li><a href="cookieServlet?action=updateCookie" target="target">Cookie值的修改a>li>
    23. <li>Cookie的存活周期li>
    24. <li>
    25. <ul>
    26. <li><a href="cookieServlet?action=defaultLife" target="target">Cookie的默认存活时间(会话)a>li>
    27. <li><a href="cookieServlet?action=deleteNow" target="target">Cookie立即删除a>li>
    28. <li><a href="cookieServlet?action=life3600" target="target">Cookie存活3600秒(1小时)a>li>
    29. ul>
    30. li>
    31. <li><a href="cookieServlet?action=testPath" target="target">Cookie的路径设置a>li>
    32. <li><a href="" target="target">Cookie的用户免登录练习a>li>
    33. ul>
    34. div>
    35. body>
    36. html>

     6、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 发送
    1. protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    2. Cookie cookie = new Cookie("path1", "path1");
    3. // getContextPath() 得到工程路径
    4. cookie.setPath( req.getContextPath() + "/abc" );
    5. //访问http://localhost:8080/13_cookie_session/abc才能看到该cookie
    6. resp.addCookie(cookie);
    7. resp.getWriter().write("创建了一个带有 Path 路径的 Cookie");
    8. }

     7、Cookie免输入用户名登录

     login.jsp 页面

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

    LoginServlet 程序

    1. public class LoginServlet extends HttpServlet{
    2. @Override
    3. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    4. String username = req.getParameter("username");
    5. String password = req.getParameter("password");
    6. if("1".equals(username)&&"1".equals(password)){
    7. Cookie cookie = new Cookie("username", username);
    8. cookie.setMaxAge(60*60*24); //当前cookie一天有效
    9. resp.addCookie(cookie);
    10. System.out.println("登录成功");
    11. }else{
    12. System.out.println("登录失败");
    13. }
    14. }
    15. }

    二、Session

    1、Session

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

    2、创建Session和获取

    request.getSession()

    • 第一次调用是:创建  Session  会话
    • 之后调用都是:获取前面创建好的  Session  会话对象。 

    isNew():判断到底是不是刚创建出来的(新的)

    • true    表示刚创建
    • false     表示获取之前创建

    每个会话都有一个身份证号。也就是  ID 值。而且这个  ID  是唯一的。 

    • getId()  得到Session  的会话 id 值。
    1. protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    2. HttpSession session = req.getSession();
    3. boolean isNew = session.isNew();
    4. String id = session.getId();
    5. resp.getWriter().write("得到的session的id是:"+id+"
      "
      );
    6. resp.getWriter().write("session是否是新创建的"+isNew+"
      "
      );
    7. }

    3、Session域数据的存取

    1. public class SessionServlet extends BaseServlet{
    2. protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    3. protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    4. req.getSession().setAttribute("key1", "value1");
    5. resp.getWriter().write("已经往 Session 中保存了数据");
    6. }
    7. protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    8. Object attribute = req.getSession().getAttribute("key1");
    9. resp.getWriter().write("从 Session 中获取出 key1 的数据是:" + attribute);
    10. }
    11. }

    4、Session生命周期控制

    1. /*
    2. 设置Session的超时时间(以秒为单位),超过指定的时长,Session 就会被销毁。
    3. 值为正数的时候,设定 Sessio 的超时时长。
    4. 负数表示永不超时
    5. */
    6. public void setMaxInactiveInterval(int interval)
    7. //获取 Session 的超时时间
    8. public int getMaxInactiveInterval()
    9. //让当前 Session 会话马上超时无效。
    10. public void invalidate()

    Session  默认的超时时间长为  30  分钟。

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

    1. <session-config>
    2. <session-timeout>30session-timeout
    3. session-config>

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

    1. <session-config>
    2. <session-timeout>20session-timeout>
    3. session-config>

    如果你想只修改个别  Session  的超时时长。就可以使用上面的  API。

    Session超时的概念介绍

     

    1. protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    2. HttpSession session = req.getSession();
    3. session.invalidate();
    4. resp.getWriter().write("Session 已经设置为超时(无效)");
    5. }
    6. protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    7. HttpSession session = req.getSession();
    8. session.setMaxInactiveInterval(3);
    9. resp.getWriter().write("当前 Session 已经设置为 3 秒后超时");
    10. }

    session.html

    1. html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    2. <html>
    3. <head>
    4. <meta http-equiv="pragma" content="no-cache" />
    5. <meta http-equiv="cache-control" content="no-cache" />
    6. <meta http-equiv="Expires" content="0" />
    7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    8. <title>Sessiontitle>
    9. <base href="http://localhost:8080/13_cookie_session/">
    10. <style type="text/css">
    11. ul li {
    12. list-style: none;
    13. }
    14. style>
    15. head>
    16. <body>
    17. <iframe name="target" width="500" height="500" style="float: left;">iframe>
    18. <div style="float: left;">
    19. <ul>
    20. <li><a href="sessionServlet?action=createOrGetSession" target="target">Session的创建和获取(id号、是否为新创建)a>li>
    21. <li><a href="sessionServlet?action=setAttribute" target="target">Session域数据的存储a>li>
    22. <li><a href="sessionServlet?action=getAttribute" target="target">Session域数据的获取a>li>
    23. <li>Session的存活li>
    24. <li>
    25. <ul>
    26. <li><a href="sessionServlet?action=defaultLife" target="target">Session的默认超时及配置a>li>
    27. <li><a href="sessionServlet?action=life3" target="target">Session3秒超时销毁a>li>
    28. <li><a href="sessionServlet?action=deleteNow" target="target">Session马上销毁a>li>
    29. ul>
    30. li>
    31. <li><a href="" target="target">浏览器和Session绑定的原理a>li>
    32. ul>
    33. div>
    34. body>
    35. html>

     

     5、浏览器和Session之间关联的技术内幕

    Session  技术,底层其实是基于  Cookie  技术来实现的。

     

     

  • 相关阅读:
    【从Python基础到深度学习】 8. VIM两种状态
    x86架构上构建arm64架构的docker镜像
    第20章 设置应用程序的样式并对其进行部署
    ATtiny88初体验(二):呼吸灯
    spring boot加mybatis puls实现,在新增/修改时,对某些字段进行处理,使用的@TableField()或者AOP @Before
    O2OA(翱途)开发平台 V8.2已发布,更安全、更高效、更开放
    PreScan快速入门到精通第二十八讲PreScan中常用传感器之TIS传感器
    通过语言模型奖励实现视频大型多模态模型的直接偏好优化
    LeetCode 2344. 使数组可以被整除的最少删除次数 最大公约数
    面试官:线程池中多余的线程是如何回收的?
  • 原文地址:https://blog.csdn.net/qq_51409098/article/details/126212179