服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|

服务器之家 - 编程语言 - JAVA教程 - servlet之cookie简介_动力节点Java学院整理

servlet之cookie简介_动力节点Java学院整理

2020-12-07 10:54fjdingsd JAVA教程

Cookie技术诞生以来,它就成了广大网络用户和Web开发人员争论的一个焦点。下面这篇文章主要给大家介绍了关于servlet之cookie简介的相关资料,文中介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。

  首先来了解什么是“会话”。会话是web技术中的一个术语,可以简单的理解为:用户打开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,这个过程称为一个会话。

  如果在打开一个浏览器访问一个页面后,再打开一个浏览器访问同一个页面,那这就是有两个会话;而打开一个浏览器访问一个页面后,通过这个页面上的某个超链接是从新的浏览器打开的,那依然只算一个会话。

  每个用户在使用浏览器与服务器进行会话的过程中,各自不可避免地会产生一些数据,而程序要想办法为每个用户保存这些数据。比如,用户点击超链接通过一个产品servlet购买了一个商品,程序应该想办法保存这个商品,以便于用户在点击付款超链接时能再从付款servlet中看到这个商品并为其买单。

  使用request对象是无法保存数据的,因为在点击商品和付款各自的servlet是发送两个不同的request请求对象,而使用servletcontext对象则会发生多个用户的线程安全问题,使用转发功能理论上可行,但是用户体验将会大打折扣,每次点击一个商品就会被要求付款。所以根据以上的需求,有两种技术来保存会话过程中产生的数据:一个是cookie,一个是session,session技术将会在之后的篇章中介绍学习。

  本篇主要先讲述servlet中的cookie技术。cookie技术是客户端技术,程序把每个用户的数据以cookie的形式写给用户各自的浏览器。当用户使用浏览器再去访问服务器时,就会带着各自的数据过去,这样web服务器处理的就是用户各自的数据了。

下图是一个会话过程中设置上一次访问时间的cookie的简单过程:

servlet之cookie简介_动力节点Java学院整理  

创建一个cookie对象就像平常创建一个java对象一样简单:

servlet之cookie简介_动力节点Java学院整理  

在使用构造器时传入cookie的名和值这样的键值对即可,我们在服务器端要获取从浏览器发来的cookie数据可以使用请求对象的request.getcookies方法获得一个cookie数组,而我们想向浏览器输出cookie时可以使用响应对象的response.addcookie(cookie)方法。

同时cookie对象还有如下一些方法:

servlet之cookie简介_动力节点Java学院整理  

  getname方法用来获取某个cookie对象的名称。

  setvalue方法和getvalue方法分别用来设置和获取某个cookie对象的值。

  setmaxage(int expires)方法是设置cookie的有效期,如果没有这句代码,cookie的有效期就是一个会话时间(即关闭浏览器该cookie就不存在了),当设置了cookie的有效期后,cookie会保存在浏览器指定的硬盘文件中,同时在这段时间内,每次访问服务器都会带着cookie过去。如果将该方法参数置为“0”,则服务器会指示浏览器删除该cookie。

  setpath方法是设置cookie的有效路径。表示在访问某些特定url时才会带cookie过去。假设某个web应用为【myservlet】,如果我们将setpath方法中的参数设置为“/myservlet”,那么访问该web应用下所有的资源都会使浏览器发送cookie过去;而如果我们将setpath方法中的参数设置为“/myservlet/pages”,那么只有访问该web应用中的【pages】下的资源才会带cookie过去,而访问该web应用中的其他资源则不会带cookie给服务器。如果我们没有设置setpath方法,那么该cookie的有效路径默认为创建cookie对象的当前程序所在目录。注意,cookie的路径是给浏览器使用的(详见《servlet的学习之web路径问题》)

  setdomain方法是设置cookie的有效域名,如: .sina.com(注意最前面有一个点)。表示当浏览器访问该域名时才会带cookie过去。但是现在浏览器基本全面阻止了这个可能作为不安全的功能,所以几乎已经被弃用。 

  举例:我们访问某个servlet,而在访问这个servlet时会将当前访问时间作为cookie中的值返回给客户端,同时下次再次访问该servlet时,会显示上一次客户端来访问的时间:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public void doget(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  
  response.setcharacterencoding("utf-8");
  response.setcontenttype("text/html;charset=utf-8");
  
  printwriter writer = response.getwriter();
  writer.write("您上次访问的时间是:");
  //获取用户上一次的访问时间并显示
  cookie[] cookies = request.getcookies();   //从请求中获取客户端发来的cookie
  for(int i=0;cookies!=null && i<cookies.length;i++) {
   if(cookies[i].getname().equals("lastaccesstime")) { //获取最后访问时间的cookie
    long mtime = long.parselong(cookies[i].getvalue()); 
    string lastaccesstime = new date(mtime).tolocalestring();
    writer.write(lastaccesstime);
   }
  }
  //将本次登录时间重新装载进cookie中并返回给客户端
  cookie timecookie = new cookie("lastaccesstime", system.currenttimemillis()+"");
  timecookie.setmaxage(1*24*60*60); //将cookie有效期置为一天
  response.addcookie(timecookie);  //将cookie传回客户端
 }

第一次访问是没有cookie的,所以看不到访问时间:

servlet之cookie简介_动力节点Java学院整理  

但是我们通过httpwatch观察response响应包中的内容已经有了“set-cookie”响应头:

servlet之cookie简介_动力节点Java学院整理  

刷新后的第二次访问就可以看到了:

servlet之cookie简介_动力节点Java学院整理  

同时观察httpwatch中request请求包的“cookie”请求头可以发现:

servlet之cookie简介_动力节点Java学院整理  

  现在我们再来通过一个案例来学习cookie,这是一个很常见的案例,比如我们在访问购物网站的时候经常会发现当浏览了这个网站内的某个商品的时候,下次继续来访问这个网站,会有一个上次浏览物品的显示。

  如果我们不是用登录后将记录保存在服务器端,而是使用cookie技术来将记录保存在客户端的浏览器中(现实生活中当然很少这样使用,这里只是作为案例学习),那么我们应该怎么做呢?

  首先我们必须在服务器要有两个servlet,一个在用户眼中是用来显示所有商品的,一个是用来显示点击某个商品之后详细信息的。

  ⑴.用来显示所有商品的servlet需要完成如下功能:

   ①     在一个部分以超链接形式将数据库中所有的商品显示在该servlet上。

   ②     在另一个部分获取用户请求中的cookie将之前浏览过的商品(通过cookie中的商品id)显示在该servlet上。

  ⑵.   用来显示点击某个商品之后详细信息的servlet需要完成如下功能:

   ①     在页面上通过超链接的url跟随的参数(即商品id)来获取该商品对象,同时将该商品对象的详细信息输出到servlet页面上。

   ②     如果是用户首次访问,将用户浏览商品的id作为cookie直接返回,而如果是用户再次访问,则需要根据一定的条件来将这些cookie的值进行调整,以便易于显示和满足用户体验。

   当然,在这之前我们还需要做些准备工作,我们需要建立商品对象,这里简单的以书为商品建立对象:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class product {
 
 private string id;
 private string name;
 private string author;
 
 public product() {
  super();
  
 }
 public product(string id, string name, string author) {
  super();
  this.id = id;
  this.name = name;
  this.author = author;
 }
 
 public string getid() {
  return id;
 }
 public void setid(string id) {
  this.id = id;
 }
 public string getname() {
  return name;
 }
 public void setname(string name) {
  this.name = name;
 }
 public string getauthor() {
  return author;
 }
 public void setauthor(string author) {
  this.author = author;
 }
}

我们还需要一个数据库来保存商品,这里我们先用一个类来来保存(数据库还没学嘛t_t!),保存数据采用map集合,这是因为如果有检索会方便:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class productdatabase {
 
 private static map<string,product> map = new hashmap<string, product>();
 
 static{
  map.put("1", new product("1","《java编程思想》","jb"));
  map.put("2", new product("2","《java核心技术》","fdaf"));
  map.put("3", new product("3","《java并发编程》","什么鬼"));
  map.put("4", new product("4","《head first 设计模式》","老王"));
  map.put("5", new product("5","《html5权威手册》","hhaa"));
 }
 
 public static map<string,product> getmap() {
 
  return map;
 }
 
}

做完了这两步,那么我们可以安心的去搞servlet了,首先是在显示所有商品的servlet:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
response.setcharacterencoding("utf-8");
  response.setcontenttype("text/html;charset=utf-8");
  
  printwriter writer = response.getwriter();
  //从数据库中取出要显示在购物网站首页的商品
  map<string,product> map = productdatabase.getmap();
  if(map == null) {
   writer.print("您访问的宝贝已下架");
   return ;
  }
  for(map.entry<string, product> en : map.entryset()) {
   writer.print("<a href='/cookieproductproject/servlet/detailgoodservlet?id="+en.getkey()+"' target='_blank' >"
              +en.getvalue().getname()+" <br/>");
  }
  
  
  //显示用户之前浏览过的商品,要从用户发送的请求中的cookie里取得
  writer.print("<br/><br/>");
  writer.print("您最近浏览过的商品: <br/>");
  
  cookie[] cookies = request.getcookies();
  for(int i=0;cookies!=null && i<cookies.length;i++ ) {
   if(cookies[i].getname().equals("producthistory")) {
    cookie cookie = cookies[i];
    string productid = cookie.getvalue();
    string[] splitid = productid.split("\\_");
    for(string sid:splitid) {
     product book = productdatabase.getmap().get(sid);
     writer.print(book.getname()+"<br/>");
    }
   }
  }
}

最后是点击某个商品显示详细信息的servlet:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
response.setcharacterencoding("utf-8");
  response.setcontenttype("text/html;charset=utf-8");
  printwriter writer = response.getwriter();
 
  //通过用户点击商品的超链接而跟随url来的id参数来获取商品的详细信息
  string productid = request.getparameter("id");
  map<string, product> map = productdatabase.getmap();
  product book = map.get(productid);
  writer.print("商品名:"+book.getname()+"<br />");
  writer.print("作者:"+book.getauthor());
  
  //同时通过cookie将用户观看的商品以cookie的形式回传给用户浏览器
  cookie[] allcookies = request.getcookies();
  
  cookie cookie = crecookie(book.getid(),allcookies);
  cookie.setmaxage(24*60*60);
  response.addcookie(cookie);

其中crecookie(string,cookie[])是自定义方法,用于获取用户的cookie并添加本次浏览商品id再作为cookie返回:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
private cookie crecookie(string id, cookie[] cookies) {
  cookie cookie = null;
  
  if(cookies == null) { //如果cookies为空,说明用户首次访问
   cookie = new cookie("producthistory", id);
   system.out.println(cookie.getvalue());
   return cookie;
  }
  for(int i=0; i<cookies.length; i++) {
   if(cookies[i].getname().equals("producthistory")){
    cookie = cookies[i];
   }
  }
  
  string historystr = cookie.getvalue(); //此时获取到的之前浏览过数据的历史记录,有多种情况
  string[] produids = historystr.split("\\_");
  
  //为了检测数组中是否有包含当前的id,建议使用集合,而且是使用链表结构的集合
  linkedlist<string> list = new linkedlist<string>(arrays.aslist(produids));
  if(list.contains(id)) {
   list.remove(id);
  }
  else if(list.size()>=3){
    list.removelast();
  }
  
  list.addfirst(id);
  
  stringbuilder sb = new stringbuilder();
  for(string sid :list) {
   sb.append(sid+"_");
  }
  sb.deletecharat(sb.length()-1);
  cookie.setvalue(sb.tostring());
  system.out.println(cookie.getvalue());
  return cookie;
}

我们在浏览器中进行首次访问:

servlet之cookie简介_动力节点Java学院整理  

随便点击个连接,可以看到该商品的详细信息(其实浏览器也偷偷将该商品的id以cookie传回了浏览器):

servlet之cookie简介_动力节点Java学院整理  

我们访问商品显示页面再次【刷新】就可以看到刚才浏览过的商品了:

servlet之cookie简介_动力节点Java学院整理  

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

延伸 · 阅读

精彩推荐