初识JSP之Cookie机制

来源:互联网 发布:淘宝身份证上传危险吗 编辑:程序博客网 时间:2024/05/17 04:54

http协议的无状态性

 

我们在进行web应用程序开发的时候,使用的是HTTP协议来传输数据,但是这个Http协议有个先天性的不足,也就是无状态,它无法对用户的状态进行保存管理。所谓的无状态就是是指,当浏览器发送请求给服务器的时候,服务器响应客户端请求,但是当同一个浏览器再次发送请求给服务器的时候,服务器并不知道它就是刚才的那个浏览器。简单地说,就是服务器不会去记得你。所以称作无状态协议。

 

由于HTTP协议是无状态的协议。一旦数据交换完毕,客户端与服务器端的连接就会关闭,再次交换数据需要建立新的连接。这就意味着服务器无法从连接上跟踪会话。但是要跟踪该会话,必须引入一种机制。


Cookie就是这样的一种机制。它可以弥补HTTP协议无状态的不足。在Session出现之前,基本上所有的网站都采用Cookie来跟踪会话。

 

会话(Session)跟踪是Web程序中常用的技术,用来跟踪用户的整个会话。常用的会话跟踪技术是Cookie与Session。Cookie通过在客户端记录信息确定用户身份,Session通过在服务器端记录信息确定用户身份。

 

cookie机制

 

什么是cookie?

 

Cookie:中文名称为“小甜饼” ,是Web服务器保存在 客户端 的一系列文本信息。

典型应用一:判定注册用户是否已经登录网站

 

典型应用二:“购物车”的处理

 

一般的视频网站中通常会记录用户看过的视频记录(浏览记录)

 

网站登录模块中也会使用cookie技术记录用户名和密码实现用户自动登录

 

Cookie的作用

 

1、对特定对象的追踪

 

2、保存用户网页浏览记录与习惯

 

3、简化登录(实现用户自动登录)

 

安全风险:容易泄露用户信息隐私

 

JSP中创建与使用Cookie

 

1、创建Cookie对象

Cookie newCookie = newCookie(Stringkey,String value);

 

2、写入Cookie对象

response.addCookie(newCookie);

 

3、读取Cookie对象

Cookie[] cookies = request.getCookies();

 

常用方法

方法名称说明

void setMaxAge(int expiry)  //设置Cookie的有效期void setValue(String value) //在Cookie创建后,对cookie进行赋值String getName()  //获取cookie的名称String getValue()  //获取cookie的值int getMaxAge()  //获取cookie的有效时间,以秒为单位

session机制


 除了使用Cookie,Web应用程序中还经常使用Session来记录客户端状态。Session是服务器端使用的一种记录客户端状态的机制,使用上比Cookie简单一些,相应的也增加了服务器的存储压力。

 

什么是session?

 

Session是另一种记录客户状态的机制,不同的是Cookie保存在客户端浏览器中,而Session保存在服务器上。客户端浏览器访问服务器的时候,服务器把客户端信息以某种形式记录在服务器上。这就是Session。客户端浏览器再次访问时只需要从该Session中查找该客户的状态就可以了。

 

Session对应的类为javax.servlet.http.HttpSession类。每个来访者对应一个Session对象,所有该客户的状态信息都保存在这个Session对象里。Session对象是在客户端第一次请求服务器的时候创建的。Session也是一种key-value的属性对,通过getAttribute(Stringkey)和setAttribute(Stringkey,Objectvalue)方法读写客户状态信息。Servlet里通过request.getSession()方法获取该客户的Session,

 

例如:

HttpSession session = request.getSession();// 获取Session对象session.setAttribute("loginTime",newDate()); // 设置Session中的属性


Session的常用方法

 

Session中包括各种方法,使用起来要比Cookie方便得多。Session的常用方法如下所示。

 

HttpSession的常用方法

方法名                                                          描 述 void setAttribute(String attribute, Objectvalue)设置Session属性。value参数可以为任何Java Object。通常为Java Bean。value信息不宜过大 String getAttribute(String attribute) 返回Session属性 Enumeration getAttributeNames() 返回Session中存在的属性名 void removeAttribute(String attribute) 移除Session属性 String getId() 返回Session的ID。该ID由服务器自动创建,不会重复 long getCreationTime() 返回Session的创建日期。返回类型为long,常被转化为Date类型,例如:DatecreateTime = new Date(session.get CreationTime()) long getLastAccessedTime() 返回Session的最后活跃时间。返回类型为long int getMaxInactiveInterval() 返回Session的超时时间。单位为秒。超过该时间没有访问,服务器认为该Session失效 void setMaxInactiveInterval(int second) 设置Session的超时时间。单位为秒 void putValue(String attribute, Objectvalue) 不推荐的方法。已经被setAttribute(String attribute, Object Value)替代 Object getValue(String attribute) 不被推荐的方法。已经被getAttribute(Stringattr)替代 boolean isNew() 返回该Session是否是新创建的 void invalidate() 使该Session失效 Tomcat中Session的默认超时时间为20分钟。通过setMaxInactiveInterval(intseconds)修改超时时间。可以修改web.xml改变Session的默认超时时间。例如修改为60分钟: <session-config><session-timeout>60</session-timeout><!-- 单位:分钟 --></session-config> 注意:<session-timeout>参数的单位为分钟,而setMaxInactiveInterval(ints)单位为秒。

Session与Cookie的对比:

Session                                                                      cookie在服务器端保存用户信息(保存在服务端的内存里面)                 在客户端保存用户信息(以文本文件的形式存在)Session中保存的是object类型                                      cookie中保存的是String类型随会话的结束而将其存储的数据销毁                                 cookie可以长期保存在客户端保存重要的信息(安全性比较高的信息)                             保存不重要的用户信息(浏览记录,访问习惯)


session 和Cookie 的共同点:

1、都是保存用户状态的一种机

2、都会过期,有时间期限限制


下面使用Cookie机制弄了个非常简单的保存用户登录状态的小例子,以便学习在JSP中如何使用cookie机制保存用户状态。例子非常简单,只是为了自己能够更好的理解。好记性不如烂键盘。。。。



1、login.jsp登录页面


<%@page import="java.net.URLDecoder"%><%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>用户登录</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>   <h1>用户登录</h1>   <hr>   <br>      <%   request.setCharacterEncoding("utf-8");      String username = "";   String password = "";      Cookie[] cookies = request.getCookies();      if(cookies != null && cookies.length > 0){   for(Cookie cookie : cookies){   if("username".equals(cookie.getName())){   username = URLDecoder.decode(cookie.getValue(), "utf-8");   }      if("password".equals(cookie.getName())){   password = URLDecoder.decode(cookie.getValue(), "utf-8");   }   }   }   %>      <br>   <br>   <form action="doLogin.jsp" name="loginForm" method="post">   <table>   <tr>   <td>用户名:</td>   <td><input type="text" name="username" value="<%=username %>"/></td>   </tr>   <tr>   <td>密码:</td>   <td><input type="password" name="password" value="<%=password %>"/></td>   </tr>   <tr>   <td colspan="2">   <input type="checkbox" name="isSaveUser" checked="checked"/>   十天内记住我的登录状态   </td>   </tr>   <tr>   <td colspan="2">   <input type="submit" value="登录"/>   <input type="reset" value="重置"/>   </td>   </tr>   </table>   </form>  </body></html>


2、doLogin.jsp处理业务逻辑


<%@page import="java.net.URLEncoder"%><%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>用户登录成功</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>  <%    request.setCharacterEncoding("utf-8");      //首先判断用户是否已经勾选记住登录状态功能(字符串数组接收)   String[] isSaveUser = request.getParameterValues("isSaveUser");      //如果勾选记住状态   if(isSaveUser != null && isSaveUser.length > 0){      //获取用户输入的用户名和密码,   String username = request.getParameter("username");   String password = request.getParameter("password");      //使用URLEncoder()进行编码,防止中文乱码   username = URLEncoder.encode(username, "utf-8");   password = URLEncoder.encode(password,"utf-8");      //实例化两个cookie对象,分别用于保存用户名和密码   Cookie unameCookie = new Cookie("username",username);   Cookie pwdCookie = new Cookie("password",password);        //设置保存的有效期限(10天)    unameCookie.setMaxAge(10*24*60*60);    pwdCookie.setMaxAge(10*24*60*60);       //使用response对象写入cookie对象   response.addCookie(unameCookie);   response.addCookie(pwdCookie);   }else{   //从request中读取cookie对象   Cookie[] cookies = request.getCookies();      if(null != cookies && cookies.length > 0){   for(Cookie cookie : cookies){   if("username".equals(cookie.getName()) || "password".equals(cookie.getName())){   //设置cookie失效   cookie.setMaxAge(0);   //重新保存   response.addCookie(cookie);   }   }   }   }   %>      <h1><%=request.getParameter("username")%>恭喜你,登录成功!</h1>   <hr>   <br>   <br>   <br>   <a href="user.jsp" target="_blank">查看我的信息</a>  </body></html>


3、user.jsp查看信息


<%@page import="java.net.URLDecoder"%><%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>用户登录成功</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>   <h1>我的信息</h1>   <hr>   <br>      <%   request.setCharacterEncoding("utf-8");      String username = "";//用户名   String password = "";//密码      //从request中读取cookie对象   Cookie[] cookies = request.getCookies();      if(cookies != null && cookies.length > 0){   for(Cookie cookie : cookies){   if("username".equals(cookie.getName())){   //使用URLDecoder进行解码   username = URLDecoder.decode(cookie.getValue(), "utf-8");   }   if("password".equals(cookie.getName())){   password = URLDecoder.decode(cookie.getValue(), "utf-8");   }   }   }   %>      <br>   <br>   用户名:<%=username %><br>   密码:<%=password %><br>  </body></html>


如果是中文,存的时候需要进行URLEncoder进行编码处理,然后取的时候用URLDecoder进行相应的解码操作

//使用URLEncoder()进行编码,防止中文乱码username = URLEncoder.encode(username, "utf-8");password = URLEncoder.encode(password,"utf-8");


request.setCharacterEncoding("utf-8");username = URLDecoder.decode(cookie.getValue(), "utf-8");


如果不做相应的处理操作,就会报下面的错误:












今天只是初步的了解了一下Cookie的机制,也算是初识cookie吧,以前听说过,但是一直不知道怎么使用,网上都说Cookie很不安全,一般项目中很少会使用到cookie,这里也是简单的了解了下cookie与session这两种机制在概念上的区别,以及cookie的一些用法,在JSP中如何去使用,而具体的原理和实现机制还没有深入的研究,实际应用中可能更加复杂,恩。。以后慢慢学习吧!加油!每天进步一点点,不久你就会看到自己的成长!
1 0