cookie使用

1.什么是cookie:

cookie是浏览器所提供的一种技术,这种技术让服务器端的程序能将一些只需保存在客户端或者在客户端进行处理的数据放在本地使用的计算机中,不许通过网络的传输,提高了网页处理的效率,减少了服务器端的负载。但是安全性较差

2.cookie和session的区别:

cookie保存在客户端,session保存在服务器,cookie可设置生存周期,默认生命周期是浏览器回话期间,关闭浏览器即结束cookie生命周期

1)、cookie数据存放在客户的浏览器上,session数据放在服务器上。

2)、cookie不是很安全,别人可以分析存放在本地的COOKIE并进行COOKIE欺骗
   考虑到安全应当使用session。

3)、session会在一定时间内保存在服务器上。当访问增多,会比较占用你服务器的性能
   考虑到减轻服务器性能方面,应当使用COOKIE。

4)、单个cookie保存的数据不能超过4K,很多浏览器都限制一个站点最多保存20个cookie。

5)、所以个人建议:
   将登陆信息等重要信息存放为SESSION
   其他信息如果需要保留,可以放在COOKIE中

2.cookie的方法:

Cookie(String name,String value)构造函数,实例化Cookie对象,同时设置名称和内容

getName()  获取cookie的名称

getValue() 获取cookie的内容

setmaxAge(int expiry)设置cookie的生命周期

 response.addCookie(c1)向客户端添加cookie对象

Cookie c[]=request.getCookies();服务器获取所有的cookie

3.实例。在details.jsp页面中的java代码中获取客户端所有的cookie,根据cookie名称判断客户端是否存在该cookie,若不存在,则向客户端增加一个cookie,并设置该cookie的生命周期;若存在,在修改该cookie的值,并将修改后的cookie重新添加到客户端。代码如下:

<%@page import="sun.misc.Request"%>

<%@page import="entity.EntityBean"%>
<%@page import="dao.ItemsDao"%>
<%@ page language="java" import="java.util.*" pageEncoding="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>My JSP 'details.jsp' starting page</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>
  <center>
   <%
 String id=request.getParameter("id");
 ItemsDao dao=new ItemsDao();
 List<EntityBean> list=dao.details(id);
 if(list!=null&&list.size()>0){
 
 EntityBean e=new EntityBean();
 e=list.get(0);
 
   %>
  <dl>
  <dt><img src="images/<%=e.getPicture()%>" width="500" height="300" border="1"></dt>
  <dd>产品名称:<%=e.getName() %></dd>
  <dd>产地:<%=e.getCity() %> 价格:<%=e.getPrice() %></dd>
  </dl>
  <a href="javascript:history.back(-1)">返回</a>
   <%
  }else
  
  {
  %>
  <p>暂没数据<%=list %></p>
  
  
  <% 
  }
 
   Cookie c[]=request.getCookies();
   String record="";
   int flag=0;
   for(int i=0;i<c.length;i++){
    if(c[i].getName().equals("history")) {
     flag=1;
     record=c[i].getValue();
      c[i].setValue(record+","+id);
      response.addCookie(c[i]);
   }
   }
   if(flag==0)
   {
   Cookie c1=new Cookie("history",id);
   c1.setMaxAge(60*60*24);
   response.addCookie(c1);
   
   } 
       %>
       <p><a href="history.jsp">浏览历史记录</a></p>
       

  </center>
  </body>
 
  
   
</html>
原文地址:https://www.cnblogs.com/binggu/p/4186837.html