之前提到Http协议时说道优点在于极大地减轻了服务器的压力,每一次连接请求不会造成不必要的连接占用,其缺点在于会频繁地连接和断开连接,请求会传输大量重复的数据。Cookie和HttpSession在某些程度行弥补了这一缺点。
会话
会话:用户从打开一个浏览器浏览各种网页到关闭浏览器的一个过程就叫一个会话。我们在浏览网页时不可避免地回产生各种数据,那么服务器和客户端如何适当地存储这些数据呢?有两种方式:
Cookie
Cookie属于客户端技术。服务器通过Servlet告诉浏览器应该缓存哪些数据,浏览器获取数据后将其保存在浏览器中,下次浏览器再去访问服务器时如果浏览器存在Cookie缓存,那么浏览器会将Cookie带给服务器。
Session
Session属于服务器技术。服务器为每个用户创建一个其独享的HttpSession对象,当不同的浏览器访问服务器时会将这些数据放在用户各自的HttpSession上。
Cookie
在刚开始的时候我在Servlet中写入了这样的代码:
@SuppressWarnings("unused")
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
final String username = request.getParameter("username");
final String password = request.getParameter("password");
System.out.println("传递参数username:" + username);
System.out.println("传递参数password:" + password);
Cookie[] cookies = request.getCookies();
for( int i=0; cookies!=null && i<cookies.length; i++ ){
Cookie cookie = cookies[i];
System.out.println("获取缓存:" + cookie.getName() + ":" + cookie.getValue());
}
if( cookies==null ){
System.out.println("加入缓存数据");
Cookie cUsername = new Cookie("username", username);
Cookie cPassword = new Cookie("password", password);
response.addCookie(cUsername);
response.addCookie(cPassword);
System.out.println("加入缓存数据完毕");
}
}
来看一下情况:
// 我们第一次打开如下链接
http://localhost:8080/MyCookie/servlet/LoginServlet?username=qdl&password=123
// sysout
传递参数username:qdl
传递参数password:123
// 第二次打开如下链接
http://localhost:8080/MyCookie/servlet/LoginServlet
// sysout
获取缓存:username:qi
获取缓存:password:123
第二次获取到的数据就是第一次的缓存。
Cookie·maxAge
默认情况下(值为-1),缓存是会话级别的,所以当我们关闭浏览器后缓存就不存在了。我们可以通过maxAge来设置关闭浏览器后缓存的有效时长,以秒为单位。cookie.setMaxAge(60*60*24),有效期为一天;
Cookie·path
cookie.setPath(path),同一目录下的浏览器请求服务器时都会将该Cookie传给服务器。
比如我们设置cookie.setPath("/MyCookie/register")
,那么当/MyCookie/register/html/register.html
请求时会传递该Cookie给服务器,但是/MyCookie/login/login.html
不会传递该Cookie,因为login.html不在/MyCookie/register
目录下。
cookie·删除
三步:
- 读取一个现有的 cookie,并把它存储在 Cookie 对象中;
- 使用 setMaxAge() 方法设置 cookie 的年龄为零,来删除现有的 cookie;
- 把这个 cookie 添加到响应头。
Cookie cookie = cookies[0];
cookie.setMaxAge(0);
response.addCookie(cookie);