zoukankan      html  css  js  c++  java
  • cookie会话

    2.1在生活会话中产生通话记录(会话数据)

    2.2软件中的会话

      一次会话:打开浏览器--》访问服务器内容--》关闭浏览器

      登陆场景:

        打开浏览器--》浏览到登陆页面--》输入用户名和密码--》访问到用户的主页(做操作)

        访问用户主页,会显示用户名

        在此次的登陆会话过程产生的数据(用户会话数据)如何保存下来?

        购物场景:

          打开浏览器--》浏览商品列表--》加入购物车(把商品信息保存下来)--》关闭浏览器

          打开浏览器--》直接进入购物车--》查看上次加入购物车的商品--》下订单--》支付

        问题:在购物会话过程中,如何保存商品信息?

        会话管理:管理浏览器客户端 和 服务器端之间会话过程产生的数据

        域对象(可以保存数据):实现资源之间数据的共享。

        request域对象

        context域对象

        登陆场景:

          小张:输入“张三”(保存数据;context.setAttribute("name","张三"))  --》用户 主页(显示张三)

          小李:输入“李四”(保存数据;context.setAttribute("name","李四"))  -->用户主页(显示“李四”)

        问题:context是所有用户共有的资源!!!会覆盖数据

          小张:输入“张三”(保存数据:request.setAttribut("name","张三"))  --》用户主页(显示“张三”)(如果要保存数据,则要使用转发来跳转页面)

      解决办法:可以使用session的域对象来保存会话的数据

      

    2.3会话技术

      cookie技术:会话数据保存在浏览器客户端。

      session技术:会话数据保存在服务器端

    3.cookie技术

      3.1特点:数据保存在浏览器客户端

      3.1cookie技术核心

        cookie类:用于存储会话数据的类(servlet    api)

        1.构造对象

          构造方法 Cookie(String name,String value)

        2.设置Cookie

          setPath(String uri):设置Cookie的有效访问路径

          setMaxAge(int expiry):设置cookie的有效时间

          setValue(String newValue): 设置cookie的有效时间

        3.发送cookie到浏览器端

          HttpServletResponse addCookie(Cookie cookie):发送cookie

        4.服务器接收cookie

          HttpServletRequest getCookies():  得到cookie

      3.3cookie原理

        1.服务器创建了一个cookie对象,把会话数据存储到cookie当中

          Cookie cookie = new Cookie("name", "cookie");

        2.服务器会发送cookie的信息到浏览器

          response.addCookie(cookie);

          举例:set-cookie:name=value(隐藏发送了set-cookie名称的响应头)

        3.浏览器得到服务器发送的cookie,然后保存在浏览器端

        4.浏览器在下次访问服务器时,会带着cookie信息

          举例:cookie:name=value(隐藏带着一个名叫cookie的请求头)

        5.服务器接收到浏览器带来的cookie信息

          request.getCookies() 得到cookie的数组

      3.4cookie细节

        1.setPath():设置cookie访问的有效路径。有效路径指的是cookie的有效路径保存在哪里,那么浏览器在有效路径下访问服务器时就会带着cookie信息,否则不带cookie信息。(默认不用设置)

        2.setMaxAge(int expiry):  设置cookie的有效时间 过期时间从不调用cookie开始计算

            正整数:表示cookie数据保存在浏览器的缓存目录中(硬盘中),数值表示保存时间

            负整数:表示cookie数据保存在浏览器的内存中。浏览器关闭cookie就丢失了(会话cookie)

            零:表示删除同名的cookie数据(构造函数中的name值要一样,但是value值无所谓)

        3.cookie的数据类型只能保存非中文字符串类型的数据,可以保存多个cookie,但是浏览器一般只允许300个cookie,每个站点最多存放20个cookie,每个cookie的大小限制为4kb

      3.5 案例:显示用户上次访问的时间

        

    1 package com.java.cookiesDemo;
    2 
    3 import java.io.IOException;
    4 import java.text.Format;
    5 import java.text.SimpleDateFormat;
    6 import java.util.Date;
    7 
    8 import javax.servlet.ServletException;
    9 import javax.servlet.http.Cookie;
    10 import javax.servlet.http.HttpServlet;
    11 import javax.servlet.http.HttpServletRequest;
    12 import javax.servlet.http.HttpServletResponse;
    13 
    14 import sun.text.resources.FormatData;
    15 
    16 public class TimeDemo extends HttpServlet {
    17 
    18 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    19 //格式化数据
    20 SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd");
    21 String curtime= format.format(new Date());
    22 
    23 //获取浏览器传过来的cookie
    24 
    25 response.setContentType("text/html;charset=utf-8");
    26 Cookie c=null;
    27 Cookie[] cookies = request.getCookies();
    28 System.out.println("准备获取cookies");
    29 if(cookies!=null){
    30 for (Cookie cookie : cookies) {
    31 if(cookie.getName().equals("lastTime")){
    32 c = cookie;
    33 break;
    34 }
    35 }
    36 }
    37 
    38 if(c!=null){
    39 String lastTime = c.getValue();
    40 c.setValue(curtime);
    41 response.getWriter().write("您上次访问的时间的为:"+lastTime+" 您现在访问的时间为:"+c.getValue());
    42 }else{
    43 //获取当前访问时间,放入cookie
    44 System.out.println("第一次访问");
    45 Date date = new Date();
    46 Cookie cookie = new Cookie("lastTime",curtime);
    47 response.addCookie(cookie);
    48 response.getWriter().write("欢迎您,现在访问时间为:"+cookie.getValue());
    49 }
    50 
    51 
    52 
    53 
    54 
    55 
    56 }
    57 
    58 }


    Product

     1 package com.java.cookies.his;
     2 
     3 public class Product {
     4     private String id;
     5     private String proName;
     6     private String proType;
     7     private Double price;
     8     public String getId() {
     9         return id;
    10     }
    11     public void setId(String id) {
    12         this.id = id;
    13     }
    14     public String getProName() {
    15         return proName;
    16     }
    17     public void setProName(String proName) {
    18         this.proName = proName;
    19     }
    20     public String getProType() {
    21         return proType;
    22     }
    23     public void setProType(String proType) {
    24         this.proType = proType;
    25     }
    26     public Double getPrice() {
    27         return price;
    28     }
    29     public void setPrice(Double price) {
    30         this.price = price;
    31     }
    32     public Product(String id, String proName, String proType, Double price) {
    33         super();
    34         this.id = id;
    35         this.proName = proName;
    36         this.proType = proType;
    37         this.price = price;
    38     }
    39     public Product() {
    40         super();
    41         // TODO Auto-generated constructor stub
    42     }
    43     @Override
    44     public String toString() {
    45         return "Product [id=" + id + ", proName=" + proName + ", proType=" + proType + ", price=" + price + "]";
    46     }
    47     
    48     
    49     
    50 }

    ProductDao

     1 package com.java.cookies.his;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 
     6 /**
     7  * 该类存放对product对象的CRUD方法
     8  * @author syousetu
     9  *
    10  */
    11 public class ProductDao {
    12 
    13     //模拟 数据库 存放所有商品
    14     private static List<Product> datas = new ArrayList<Product>();
    15     
    16     /**
    17      * 静态代码块,初始化商品数据 
    18      * 只执行一次
    19      */
    20     
    21     static{
    22         for (int i = 0; i < 100; i++) {
    23             datas.add(new Product(i+"","笔记本"+i,"LN00"+i,34.5+i));
    24         }
    25         
    26         
    27     }
    28     
    29     
    30     /**
    31      * 提供查询所有商品的方法
    32      */
    33     
    34     public List <Product> findAll(){
    35         return datas;
    36     }
    37     
    38     /**
    39      * 提供查询单个商品的方法
    40      */
    41     
    42     public Product findById(String id){
    43         for (Product product : datas) {
    44             if(product.getId().equals(id)){
    45                 return product;
    46             }
    47         }
    48         return null;
    49         
    50     }
    51     
    52 }

    listServlet

     1 package com.java.cookies.his;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 import java.util.List;
     6 
     7 import javax.servlet.ServletException;
     8 import javax.servlet.http.Cookie;
     9 import javax.servlet.http.HttpServlet;
    10 import javax.servlet.http.HttpServletRequest;
    11 import javax.servlet.http.HttpServletResponse;
    12 
    13 /**
    14  * 查询所有商品的servlet
    15  * 
    16  * @author syousetu
    17  *
    18  */
    19 public class listServlet extends HttpServlet {
    20 
    21     protected void doGet(HttpServletRequest request, HttpServletResponse response)
    22             throws ServletException, IOException {
    23         response.setContentType("text/html;charset=utf-8");
    24 
    25         // 1.读取数据库,查询所有的商品列表
    26         ProductDao pDao = new ProductDao();
    27         List<Product> lists = pDao.findAll();
    28 
    29         // 2.把商品显示到浏览器
    30         PrintWriter writer = response.getWriter();
    31         String html = "";
    32         html += "<html>";
    33 
    34         html += "<head>";
    35         html += "<title>";
    36         html += "</title>";
    37         html += "</head>";
    38 
    39         html += "<body>";
    40 
    41         html += "<form action=''>";
    42 
    43         html += "<table border='1' align='center' width='600px'>";
    44         html += "<tr>";
    45         html += "<th>商品编号</th>";
    46         html += "<th>商品名称</th>";
    47         html += "<th>商品型号</th>";
    48         html += "<th>商品价格</th>";
    49         html += "</tr>";
    50         if (lists != null) {
    51 
    52             for (Product product : lists) {
    53                 html += "<tr>";
    54                 html += "<td>" + product.getId() +"</td>";
    55                 html += "<td>" + "<a href=/Http/oneServlet?proId="+product.getId()+">"+product.getProName() + "</td>";
    56                 html += "<td>" + product.getProType() + "</td>";
    57                 html += "<td>" + product.getPrice() + "</td>";
    58                 html += "</tr>";
    59             }
    60 
    61         }
    62 
    63         html += "</table>";
    64 
    65         html += "</form>";
    66 
    67         html += "</body>";
    68         html += "</html>";
    69         writer.write(html);
    70 
    71     }
    72 
    73     protected void doPost(HttpServletRequest request, HttpServletResponse response)
    74             throws ServletException, IOException {
    75         doGet(request, response);
    76     }
    77 
    78 }

    oneServlet

      1 package com.java.cookies.his;
      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 public class oneServlet extends HttpServlet {
     13 
     14     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     15         String id = request.getParameter("proId");
     16         ProductDao pDao = new ProductDao();
     17 //        Cookie cookie  = null;
     18         
     19         response.setContentType("text/html;charset=utf-8");
     20         String html="";
     21         PrintWriter writer = response.getWriter();
     22         Product p = null;
     23         p = pDao.findById(id);
     24         
     25         
     26         /**
     27          * 用cookie来存储历史浏览过的数据
     28          */
     29         //先拿到浏览器穿过来的cookies
     30         Cookie [] cookies = null;
     31         cookies = request.getCookies();
     32         String ids="";
     33         if(cookies!=null){
     34             for (Cookie cookie : cookies) {
     35                 if(cookie.getName().equals("history")){
     36                     ids=cookie.getValue();
     37                     cookie.setValue(p.getId()+","+ids);
     38                     cookie.setMaxAge(1*30*24*60*60);
     39                     response.addCookie(cookie);
     40                 }
     41             }
     42         }
     43         
     44         /**
     45          * 对于获得的编号的操作
     46          * 1.先将字符串转换为字符数组
     47          * 2.再将字符数组转换为集合Connection conn =  Arrays.asList(字符数组 )
     48          * 3.然后将集合转换为链表进行操作    new LinkedList(conn);
     49          *     链表集合,有助于进行增删该查操作
     50          */
     51         
     52         //用来存放分割后的id
     53         String []id2 = null;
     54         //将商品编号进行分割
     55         if(!("".equals(ids))){
     56             id2 = ids.split(",");
     57         }
     58         
     59         
     60         
     61         //第一次浏览商品
     62         if("".equals(ids) || cookies==null){
     63             Cookie cookie  = new Cookie("history",p.getId());
     64             cookie.setMaxAge(1*30*24*60*60);
     65             response.addCookie(cookie);
     66         }
     67         
     68         if(p!=null){
     69             //把商品写出去
     70             html+="<html>";
     71             html+="<head>";
     72             html+="<title>";
     73             html+="</title>";
     74             html+="<head>";
     75             html+="<body>";
     76             html+="<p>商品编号:"+p.getId()+"</p>";
     77             html+="<p>商品名称:"+p.getProName()+"</p>";
     78             html+="<p>商品型号:"+p.getProType()+"</p>";
     79             html+="<p>商品价格:"+p.getPrice()+"</p>";
     80             
     81             //显示历史浏览过的商品
     82             html+="<h4>历史浏览</h4>";
     83             html+="<table>";
     84             html+="<tr>";
     85             html+="<th>商品名称</th>";
     86             html+="<th>商品价格</th>";
     87             html+="</tr>";
     88             if(id2!=null){
     89                 for (String string : id2) {
     90                     html+="<tr>";
     91                     html+="<td>"+"<a href='"+request.getContextPath()+"/oneServlet?proId="+pDao.findById(string).getId()+"'>"+pDao.findById(string).getProName()+"</a>"+"</td>";
     92                     html+="<td>"+pDao.findById(string).getPrice()+"</td>";
     93                     html+="</tr>";
     94                 }
     95                 
     96                 
     97             }
     98             
     99             
    100             
    101             html+="</table>";
    102             
    103             html+="<center><a href='"+request.getContextPath()+"/listServlet'>[返回列表]</a></center>";
    104             html+="</body>";
    105             html+="</html>";
    106             
    107         }
    108         
    109         writer.write(html);
    110         
    111         
    112     }
    113 
    114 
    115 }
  • 相关阅读:
    devDependencies和dependencies的版本写法
    dependencies 与 devDependencies 的区别
    Java +selenium Navigation接口介绍
    Java + selenium window()接口方法介绍
    Java + selenium Timeout接口用法介绍
    Java + selenium 启动谷歌浏览器
    selenium 3 下载 + Java使用
    Rsync 实现服务器文件的同步——服务端的安装配置
    selenium V1.0和V2.0差别对比
    PHP的安装配置
  • 原文地址:https://www.cnblogs.com/syousetu/p/6545848.html
Copyright © 2011-2022 走看看