zoukankan      html  css  js  c++  java
  • 7、Servlet会话跟踪

    一、会话跟踪:

      不管操作多少功能,都是与当前登录用户相关的信息,当前的登录用户始终没有改变,也就是用户名和密码都没有丢失。但HTTP协议是一个无状态的协议,当一个客户向服务器发出请求(request),在服务器返回响应(response)后,连接就关闭了。这时,在服务器端不保留连接相关的信息,因此当下一次请求连接时,服务器已没有以前连接的信息了,也就无法判断这一次连接和以前的连接是否属于同一客户,也就是说Web服务器无法跟踪客户状态。在 Servlet 规范中,常用以下两种机制完成会话跟踪:

      a)使用持续的Cookie
      b)使用Session(会话)机制

    二、Cookie:Cookie以“名-值”对的形式保存数据

      1.创建Cookie对象: new Cookie(name,value);
      2.设置最大时效 :setMaxAge(int age);
      3.将Cookie放入到HTTP响应报头:  addCookie(Cookie cookie);

      【注意】如果创建了一个cookie,并将它发送到浏览器,默认情况下它是一个会话级别的cookie,他将被存储在浏览器的内存中,用户退出浏览器之后被删除。若希望浏览器将该cookie存储在磁盘上,则需要使用setMaxAge,并给出一个以秒为单位的时间。将最大时效设为0则是命令浏览器删除该cookie。

      1)、将数据写入Cookie中:

     1 package com.st.user;
     2 
     3 import java.io.IOException;
     4 
     5 import javax.servlet.ServletException;
     6 import javax.servlet.http.Cookie;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 
    11 @SuppressWarnings("serial")
    12 public class UserLoginTest extends HttpServlet{
    13     @Override
    14     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    15             throws ServletException, IOException {
    16         // TODO Auto-generated method stub
    17     }
    18     @Override
    19     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    20             throws ServletException, IOException {
    21         // TODO Auto-generated method stub
    22         req.setCharacterEncoding("UTF-8");  //post乱码专用解决方式
    23         String userName = req.getParameter("userName");
    24         String passWord = req.getParameter("passWord");
    25         System.out.println(userName);
    26         System.out.println(passWord);
    27         Cookie cookieByName = new Cookie("userName",userName);
    28         Cookie cookieByPassWord = new Cookie("passWord", passWord);
    29         /*cookieByName.setMaxAge(24 * 60 * 60); //设置在硬盘上保存的时间,以秒为单位。
    30         cookieByPassWord.setMaxAge(24 * 60 * 60);因为保存在硬盘上,所以即便是服务器重启了依然可以访问*/
    31         resp.addCookie(cookieByName);
    32         resp.addCookie(cookieByPassWord);
    33         //转发
    34 //        req.getRequestDispatcher("/home.jsp").forward(req, resp);
    35         //重定向
    36         resp.sendRedirect("home.jsp");
    37     }
    38 }
    View Code

      2)、读取cookie中的值:

     1 package com.st.user;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 
     6 import javax.servlet.ServletException;
     7 import javax.servlet.http.Cookie;
     8 import javax.servlet.http.HttpServlet;
     9 import javax.servlet.http.HttpServletRequest;
    10 import javax.servlet.http.HttpServletResponse;
    11 
    12 @SuppressWarnings("serial")
    13 public class BookServletTest extends HttpServlet {
    14 
    15     public void doGet(HttpServletRequest request, HttpServletResponse response)
    16             throws ServletException, IOException {
    17     }
    18     public void doPost(HttpServletRequest request, HttpServletResponse response)
    19             throws ServletException, IOException {
    20         request.setCharacterEncoding("UTF-8");
    21         System.out.println(request.getParameter("bookName"));
    22         Cookie cookie []= request.getCookies();  //返回的是cookie的一个数组
    23         for(Cookie c: cookie){
    24             if("userName".equals(c.getName()))
    25                 System.out.println("userName="+c.getValue());
    26             else if("passWord".equals(c.getName()))
    27                 System.out.println("password="+c.getValue());
    28         }
    29         response.setContentType("text/html");
    30         PrintWriter out = response.getWriter();
    31         out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
    32         out.println("<HTML>");
    33         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
    34         out.println("  <BODY>");
    35         out.print("    This is ");
    36         out.print(this.getClass());
    37         out.println(", using the POST method");
    38         out.println("  </BODY>");
    39         out.println("</HTML>");
    40         out.flush();
    41         out.close();
    42     }
    43 }
    View Code

    二、Session:Session机制采用的是在服务器端保持 HTTP 状态信息的方案。会话范围是某个用户从首次访问服务器开始,到该用户关闭浏览器结束。会话时效采用间隔计时的方式。

      a)、写入Session:

     1 package com.st.session;
     2 
     3 import java.io.IOException;
     4 import java.util.HashMap;
     5 import java.util.Map;
     6 
     7 import javax.servlet.ServletException;
     8 import javax.servlet.http.HttpServlet;
     9 import javax.servlet.http.HttpServletRequest;
    10 import javax.servlet.http.HttpServletResponse;
    11 import javax.servlet.http.HttpSession;
    12 
    13 public class UserLoginTest extends HttpServlet {
    14 
    15     public void doGet(HttpServletRequest request, HttpServletResponse response)
    16             throws ServletException, IOException {
    17 
    18     }
    19 
    20     public void doPost(HttpServletRequest request, HttpServletResponse response)
    21             throws ServletException, IOException {
    22         request.setCharacterEncoding("UTF-8");  //post乱码专用解决方式
    23         String userName = request.getParameter("userName");
    24         String passWord = request.getParameter("passWord");
    25         System.out.println(userName);
    26         System.out.println(passWord);
    27         HttpSession session = request.getSession();//如果当前存在session,则使用已存在的session如果当前不存在session,则创建一个新的session
    28         session.setAttribute("userName", userName);
    29         session.setAttribute("passWord", passWord);
    30         //session可以载入任意类型的值
    31         Map<String, String> map =new HashMap<String, String>();
    32         map.put("userName", userName);
    33         map.put("passWord", passWord);
    34         session.setAttribute("user", map);
    35         session.setMaxInactiveInterval(60);//设置该Session的最大时效,以S为单位
    36         System.out.println(request.getContextPath());
    37 //        request.getRequestDispatcher("/home.jsp").include(request, response);
    38         response.sendRedirect("../home.jsp");
    39     }
    40 }
    View Code

      b)、读取session:

     1 package com.st.session;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 import java.util.Map;
     6 
     7 import javax.servlet.ServletException;
     8 import javax.servlet.http.HttpServlet;
     9 import javax.servlet.http.HttpServletRequest;
    10 import javax.servlet.http.HttpServletResponse;
    11 import javax.servlet.http.HttpSession;
    12 
    13 public class SessionTest extends HttpServlet {
    14     public void doGet(HttpServletRequest request, HttpServletResponse response)
    15             throws ServletException, IOException {
    16 
    17     }
    18     public void doPost(HttpServletRequest request, HttpServletResponse response)
    19             throws ServletException, IOException {
    20         request.setCharacterEncoding("UTF-8");  //post乱码专用解决方式
    21         System.out.println(request.getParameter("bookName"));
    22         HttpSession session = request.getSession();
    23         System.out.println("session="+session); //如果session里没有对应的属性名,则返回null
    24         String userName = (String)session.getAttribute("userName");
    25         String passWord = (String)session.getAttribute("passWord");
    26         System.out.println("userName="+userName+",passWord="+passWord);
    27         
    28         Map<String, String> map = (Map<String, String>)session.getAttribute("user");
    29         System.out.println("The userName is "+map.get("userName")+",passWord = "+map.get("passWord"));
    30         response.sendRedirect("../home.jsp");
    31     }
    32 
    33 }
    View Code

      

    三、Cookie和Session的区别:

      1、存放的位置不同:

        a)、Cookie存放于客户端的临时文件夹中

        b)、Session存放于服务器端,服务器为每个用户创建一个独立的Session域对象。

      2、生命周期不同:

        a)、如果不设置过期时间,则表示这个cookie生命周期为浏览器会话期间,只要关闭浏览器窗口,cookie就消失了。另外如果设置了Cookie的最大时效(比如设置一个小时),则从设置完成开始计时,当时间达到1个小时后,Cookie就自动失效了。

        b)、Session的默认时效为20分钟(当然这个默认值也是可以自己设置的),其计时方式是间隔的,即从创建开始到20分钟后Session就会自动被销毁,但是如果在第19分59秒的时候访问了Session,那么这个生命周期又将从0开始计时,直到用户在连续的20分钟内都没有访问后Session才被销毁。

      3、安全性不同:

        a)、Cookie存放在客户端的临时文件夹中不安全

        b)、Session存放在服务器的内存中,所以相对来说要安全得多

      4、作用范围不同

        a)、Cookie可以为多个用户浏览器共享

        b)、Session只为同一个用户浏览想用

  • 相关阅读:
    darknet版本yolov3训练与测试
    Package opencv was not found in the pkg-config search path.
    ubuntu18.4下安装Anaconda及conda命令
    ubuntu18.4编译opencv4.1
    ubuntu18.4下cuda卸载
    抽象基类、访问控制与继承和继承中的类作用域
    C++ Pirmer : 第十五章 : 面向对象程序设计之基类和派生的定义、类型转换与继承与虚函数
    C++ Primer : : 第十四章 : 重载运算符与类型转换之类型转换运算符和重载匹配
    C++ Pirmer : 第十四章 : 重载运算符与类型转换之函数调用运算符与标准库的定义的函数对象
    C++ Primer : 第十四章 : 重载运算与类型转换之重载运算符
  • 原文地址:https://www.cnblogs.com/czj-zhm/p/6489624.html
Copyright © 2011-2022 走看看