Cookie简介

初识Cookie及操作方法

Posted by Mr.Gao on May 4, 2020

Web开发中,经常会遇到页面之间进行传值的操作,必须通过服务器,使用url传值、隐藏表单方法均能实现。

我们假设,页面1中定义一个变量,需要传输到页面2中,要求值的数据不被看到,使用url传值是通过url方法,传递的数据可能被看到。也可也使用隐藏表单,但传递的值会在客户端的源码中被看到。今天介绍另一种方法—-Cookie。

在页面之间传递数据的过程中,Cookie是一种常见的方法。Cookie是一个小的文本数据,由服务器端生成,发送给客户端浏览器,客户端如果浏览器设置为启动Cookie,则会将这个小文本数据保存在某个目录下的文本文件内。下次登录同一网站,客户端浏览器会自动将Cookie读入之后,传给服务器端。一般情况下,Cookie中的值是以key-value(键值对)的形式进行表达的。

写Cookie时,主要用到以下几个方法:

1、response.addCookie(Cookie c)        //通过该方法,将Cookie写入客户端。  
2、Cookie.setMaxAge(int Second)        //通过该方法,设置Cookie的存活时间。参数表示存活的秒数。  
3、request.getCookies()                //从客户端获取Cookie内容,主要通过调用该方法,读取从客户端传过来的Cookie,以数组形式返回,读取数组之后,一般需要进行遍历。  

示例: 假设页面1中定义了一个数值变量,并显示其平方;要求在页面2中显示其立方

| 页面1: cookieP1.jsp

<%@ 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 'cookieP1.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>
    <%
    	//定义一个变量
    	String str = "12";
    	int number = Integer.parseInt(str);
     %>
     <p>该数字的平方为 : <%=number*number %></p>
     <%
     	//将str存入Cookie
     	Cookie cookie = new Cookie("number",str);
     	//设置Cookie的存活期为600秒
     	cookie.setMaxAge(600);
     	//将cookie保存于客户端
     	response.addCookie(cookie);
      %>
      <a href="cookieP2.jsp">到达p2</a>
  </body>
</html>

| 页面2: cookieP2.jsp

<%@ 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 'cookieP2.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>
    <%
    	//从 Cookie获得 number
    	String str = null;
    	Cookie[] cookies = request.getCookies();
    	for(int i = 0; i < cookies.length; i++){
    		if(cookies[i].getName().equals("number")){            //根据Cookie的键名进行对比查找
    			str = cookies[i].getValue();                  //若查找成功则返回键值
    			break;
    		}
    	}
    	int number = Integer.parseInt(str);
     %>
     <p>该数字的立方为<%=number*number*number %></p>
  </body>
</html>

在客户端的浏览器,看不到任何有关于数据的信息。但也不能说明Cookie是安全的。因为客户端存储的Cookie文件可以为别人获知。

解决Cookie安全的办法有很多,常见的有以下几种:

|1. 替代Cookie。将数据保存在服务器端,可选的是session方案。 |2. 为Cookie赋空值、设置Cookie的失效时间、浏览器删除Cookie、禁用Cookie。

总结:Cookie在开发中应用还是很广泛的,原因如下:

|1. 减少对于安全性要求不高网站的验证工作的负担。
|2. Cookie可以帮助服务器端保存多个状态信息,但是不用服务器专门分配存储资源。
|3. Cookie可以持久保持一些和客户相关的信息。