JavaWeb---Cookie的使用

来源:互联网 发布:豆瓣电影评论数据集 编辑:程序博客网 时间:2024/05/19 09:17

1. 什么是Cookie?

Cookie是一种在客户端保存信息的技术。读者在浏览网页时可能会注意到这样的现象,如在打开某个登录网页时,在第一次打开时,用户名文本框是空的,当输入一个用户名,并成功登录后。在第二次打开这个登录网页时,在第一次输入的用户名会被自动填入这个用户名文本框,就算重启计算机后,仍然如此。其实这就是Cookie所起的作用

2. Cookie的作用

Cookie是Web服务器保存在客户端的一系列文本信息

 Cookie的作用

    a)  对特定对象的追踪

    b)  统计网页浏览次数

    c)  简化登录

 安全性能

    d)  容易信息泄露

3.使用Cookie进行登陆

 String rn = request.getParameter("r1");
  String name = request.getParameter("user");
  String pwd = request.getParameter("pwd");
  if (rn.equals("0")) {
   Cookie tempCookie = new Cookie("temp", "87564321");
   tempCookie.setMaxAge(-1);
   response.addCookie(tempCookie);
  } else if (rn.equals("1")) {
   // 创建Cookie对象   Cookie的value值不能出现:;[{}]等符号,只能用逗号分隔
   Cookie cookie1 = new Cookie("user", name);
   Cookie cookie2 = new Cookie("pwd", pwd);
   // 设置Cookie有效时间
   cookie1.setMaxAge(60 * 60 * 24);
   cookie2.setMaxAge(60 * 60 * 24);
   // 设置Cookie存储路径
   cookie1.setPath("/");
   cookie2.setPath("/");
   // 添加Cookie到响应对象
   response.addCookie(cookie1);
   response.addCookie(cookie2);
  } else if (rn.equals("7")) {
   // 创建Cookie对象
   Cookie cookie2 = new Cookie("user", name);
   // 设置Cookie有效时间
   cookie2.setMaxAge(60 * 60 * 24 * 7);
   // 设置Cookie存储路径
   cookie2.setPath("/");
   // 添加Cookie到响应对象
   response.addCookie(cookie2);
  }

4.读取Cookie进行登陆验证

<%  //读取Cookie
   String name = "";
   String pwd = "";
   //通过请求对象的获得Cookie集合的方法 得到一个Cookie数组
   Cookie[] cookie = request.getCookies();
   for (int i = 0; i < cookie.length; i++) {
    //每一个数组元素都是一个Cookie对象
    Cookie c = cookie[i];
    if (c.getName().equals("user")) {
     name = c.getValue();
     //处理中文进行解码  java.net.URLDecoder
     name=URLDecoder.decode(name);
     break;
    }
    if (c.getName().equals("pwd")) {
     pwd = c.getValue();
     break;
    }
   }
  %>

 

0 0
原创粉丝点击