MENU

Cookie读写操作

September 20, 2018 • Read: 4057 • JSP阅读设置

Cookie

浏览器与WEB服务器之间是使用HTTP协议进行通信的,当某个用户发出页面请求时,WEB服务器只是简单的进行响应,然后就关闭与该用户的连接。因此当一个请求发送到WEB服务器时,无论其是否是第一次来访,服务器都会把它当作第一次来对待,这样的不好之处可想而知。为了弥补这个缺陷,Netscape开发出了cookie这个有效的工具来保存某个用户的识别信息。cookies是一种WEB服务器通过浏览器在访问者的硬盘上存储信息的手段:Netscape Navigator使用一个名为cookies.txt本地文件保存从所有站点接收的Cookie信息;而IE浏览器把Cookie信息保存在类似于 C://windows//cookies的目录下。当用户再次访问某个站点时,服务端将要求浏览器查找并返回先前发送的Cookie信息,来识别这个用户

jsp是通过以下语法格式来创建Cookie的

Cookie cookie_name =new Cookie("Parameter","Value");
//例如
Cookie username_Cookie = new Cookie("username","zhangsan"); 
response.addCookie(username_Cookie);

JSP是调用Cookie对象相应的构造函数Cookie(name,value)用合适的名字和值来创建Cookie,然后Cookie可以通过response的addCookie方法加入到Set-Cookie应答头

Cookie的各种方法

  • String getComment():返回cookie中注释,如果没有注释的话将返回空值
  • String getDomain():返回cookie中Cookie适用的域名 使用getDomain() 方法可以指示浏览器把Cookie返回给同 一域内的其他服务器,而通常Cookie只返回给与发送它的服务器名字完全相同的服务器。注意域名必须以点开始(例如.wmathor.com)
  • int getMaxAge():返回Cookie过期之前的最大时间,以秒计算
  • String getName():返回Cookie的名字
  • String getPath():返回Cookie适用的路径。如果不指定路径,Cookie将返回给当前页面所在目录及其子目录下的所有页面
  • boolean getSecure():如果浏览器通过安全协议发送cookies将返回true值,如果浏览器使用标准协议则返回false值
  • String getValue():返回Cookie的值
  • int getVersion():返回Cookie所遵从的协议版本
  • void setComment(String purpose):设置cookie注释
  • void setDomain(String pattern):设置cookie中Cookie适用的域名
  • void setMaxAge(int expiry):以秒计算,设置Cookie过期时间
  • void setValue(String newValue):Cookie创建后设置一个新的值
  • void setVersion(int v):设置Cookie遵从的协议版本
  • void setSecure(boolean flag):指出浏览器使用的安全协议,例如HTTPS或SSL

写入Cookie

<%@ 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>Cookie Write 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">
</head>
<body>
    <% 
        Cookie cookie_a = new Cookie("a_name","a_value");//name,value
        response.addCookie(cookie_a);
        
        Cookie cookie_b = new Cookie("b_name","b_value");
        cookie_b.setMaxAge(30 * 24 * 60 * 60);//单位是秒
        response.addCookie(cookie_b);
        
        Cookie cookie_c = new Cookie("c_name","c_value");
        cookie_c.setMaxAge(-1);
        //-1是一个session Cookie,浏览器打开有用,关闭时删除
        //cookie_c.setPath(当前路径);默认有一个调用
        response.addCookie(cookie_c);
        
        Cookie cookie_d = new Cookie("d_name","d_value");
        cookie_d.setMaxAge(30 * 24 * 60 * 60);//单位是秒
        cookie_d.setPath("/jsp");
        response.addCookie(cookie_d);
        
        Cookie cookie_e = new Cookie("e_name","e_value");
        cookie_e.setMaxAge(30 * 24 * 60 * 60);//单位是秒
        cookie_e.setPath("/");//服务器的根目录
        response.addCookie(cookie_e);
    %>
    <!--HttpSession 
            设置Session的最大呆滞时间
            销毁Session invalidate
            获取SessionID SessionId
            Object getAttribute(String name)
            void setAttribute(String name,Object value);
            
        application
            ServerletContext
            Object getAttribute(String name)
            void setAttribute(String name,Object value);
    -->    
    <a href = "/jsp/c03/cookie.jsp">返回</a>
</body>
</html>

读Cookie

<%@ 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>Cookie Read 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">
<jsp:include page = "../res.jsp"></jsp:include>
</head>
<body class = "container">
    <%
        Cookie[] cookies = request.getCookies();
        if(cookies == null || cookies.length == 0) {
            out.print("没有Cookie");
            return;
        }
    %>
    <table class = "table table-bordered">
    <% 
        for(Cookie cookie : cookies) {
    %>
            <tr>
                <td><%= cookie.getName() %></td>
                <td><%= cookie.getValue() %></td>
                <td><%= cookie.getMaxAge() %></td>
                <td><%= cookie.getDomain() %></td>
                <td><%= cookie.getPath() %></td>
            </tr>
    <%
        }
    %>
    </table>
    <% 
                
    %>
    <a href = "/jsp/c03/cookie.jsp">返回</a>
</body>
</html>
Last Modified: September 6, 2021
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment

已有 1 条评论
  1. 女生游戏 女生游戏

    Cookie是很方便,了解越多功能越强大