JSP Cookie 操作

本文详细介绍了如何在JSP文件中使用JSP操作Cookie,包括如何写入和读出Cookie,以及需要注意的问题,如Cookie的兼容性和内容字符限制。

<TITLE>Setting and Reading Cookies</TITLE>
    </HEAD>
    <BODY
        <%
        Cookie[] cookies = request.getCookies();
        boolean foundCookie = false;

        for(int i = 0; i < cookies.length; i++) {
            Cookie c = cookies[i];
            if (c.getName().equals("color")) {
                out.println("bgcolor = " + c.getValue());
                foundCookie = true;
            }
       

        if (!foundCookie) {
            Cookie c = new Cookie("color", "cyan");
            c.setMaxAge(24*60*60);
            response.addCookie(c);
        }
        %>
        >
        <H1>Setting and Reading Cookies</H1>
        This page will set its background color using a cookie.
    </BODY>
</HTML>
资料引用:http://www.knowsky.com/350176.html

 

一、 前言

说起来,Cookie应该是一种应用较久的技术了。早在HTML刚刚出现的时候,在每个独立的页面之间没有办法记录和标识不同的用户。后来人们就发明了Cookie技术,当用户访问网页时,它能够在访问者的机器上创立一个文件,我们把它叫作Cookie,写一段内容进去,来标识不同的用户。如果下次用户再访问这个网页的时候,它又能够读出这个文件里面的内容,这样网页就知道上次这个用户已经访问过该网页了。

虽然现在网页的制作技术比起几年以前已经发展了许多。不过有些时候,Cookie还是能够帮我们很多忙的。接下来,我们就来看看,如何在写JSP文件的时候,用JSP操作Cookie。


二、 写入Cookie

其实用JSP操作Cookie是非常简单的,我们来看下面一段JSP程序:

 

<html>
<head>........(中间略)
</head>
<body>
<%
String cookieName="Sender";
Cookie cookie=new Cookie(cookieName, "Test_Content");
cookie.setMaxAge(10);
response.addCookie(cookie);
%>
........(其他内容)
</body>
</html>

 

这样我们就设置了一个Cookie,很简单吧?

我们来仔细研究一下这段代码:

Cookie cookie=new Cookie(cookieName, "Test_Content");

这一行建立了一个Cookie对象,初始化有两个参数,第一个参数cookieName定义了Cookie的名字,后一个参数,也是一个字符串,定义了Cookie的内容。也就是我们希望网页在用户的机器上标识的文件内容。

接下来一行:cookie.setMaxAge(10),调用了Cookie中的setMaxAge方法,设定Cookie在用户机器硬盘上的存活期为10秒。一个Cookie在用户的硬盘里面存在的时间并不是无限期的,在建立Cookie对象的时候,我们必须制定Cookie的存活期,超过了这个存活期后,Cookie文件就不再起作用,会被用户的浏览器自行删除。如果我们希望用户在下次访问这个页面的时候,Cookie文件仍然有效而且可以被网页读出来的话,我们可以将Cookie的存活期设得稍微长一些。比如cookie.setMaxAge(365*24*60*60)可以让Cookie文件在一年内有效。

三、 读出Cookie

Cookie文件创建好后,自然还需要我们把它读出来,否则我们不是白费力气吗?接下来我们看看如何读出在用户硬盘上的Cookie。

 

<html>
<head>........(中间略)
</head>
<body>
<table border=1>
<tr><td>Name</td><td>value</td></tr>
<%
Cookie cookies[]=request.getCookies();
Cookie sCookie=null;
String svalue=null;
String sname=null;
for(int i=0;i<cookies.length;i++)
{
sCookie=cookies[i];
svalue=sCookie.getValue();
sname=sCookie.getName();
%>
<tr><td><%=name%></td><td><%=svalue%></td></tr>
<%
}
%>
</table>
........(其他内容)
</body>
</html>

 

这一小段JSP文件可以读出用户硬盘上的所有有效的Cookie,也就是仍然在存活期内的Cookie文件。并用表格的形式列出每个Cookie的名字和内容。

我们来逐行分析一下这段代码:

Cookie cookies[]=request.getCookies() 我们用request.getCookies()读出用户硬盘上的Cookie,并将所有的Cookie放到一个cookie对象数组里面。

接下来我们用一个循环语句遍历刚才建立的Cookie对象数组,我们用sCookie=cookies[i]取出数组中的一个Cookie对象,然后我们用sCookie.getValue()和sCookie.getName()两个方法来取得这个Cookie的名字和内容。

通过将取出来的Cookie的名字和内容放在字符串变量中,我们就能对其进行各种操作了。在上面的例子里,可通过循环语句的遍历,将所有Cookie放在一张表格中进行显示。


四、 需要注意的一些问题

通过上面两个简单的例子,可以看到,用JSP进行Cookie的操作,是非常简单的。不过我们在实际操作中还要注意一些问题:

1. Cookie的兼容性问题

Cookie的格式有2个不同的版本,第一个版本,我们称为Cookie Version 0,是最初由Netscape公司制定的,也被几乎所有的浏览器支持。而较新的版本,Cookie Version 1,则是根据RFC 2109文档制定的。为了确保兼容性,JAVA规定,前面所提到的涉及Cookie的操作都是针对旧版本的Cookie进行的。而新版本的Cookie目前还不被Javax.servlet.http.Cookie包所支持。

2. Cookie的内容

同样的Cookie的内容的字符限制针对不同的Cookie版本也有不同。在Cookie Version 0中,某些特殊的字符,例如:空格,方括号,圆括号,等于号(=),逗号,双引号,斜杠,问号,@符号,冒号,分号都不能作为Cookie的内容。这也就是为什么我们在例子中设定Cookie的内容为“Test_Content”的原因。

虽然在Cookie Version 1规定中放宽了限制,可以使用这些字符,但是考虑到新版本的Cookie规范目前仍然没有为所有的浏览器所支持,因而为保险起见,我们应该在Cookie的内容中尽量避免使用这些字符。

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html lang="zh-CN" class="bootstrap-admin-vertical-centered"> <head> <meta charset="UTF-8"> <title>图书馆管理系统</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="static/css/bootstrap.min.css"> <link rel="stylesheet" href="static/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="static/css/bootstrap-admin-theme.css"> <link rel="stylesheet" href="static/css/bootstrap-admin-theme.css"> <script src="static/js/bootstrap.min.js"></script> <script src="static/jQuery/jquery-3.1.1.min.js"></script> <script src="static/ajax-lib/ajaxutils.js"></script> <script src="static/js/login.js"></script> </head> <style type="text/css"> .alert{ margin: 0 auto 20px; text-align: center; } </style> <script src="static/js/jquery.min.js"></script> <script src="static/js/bootstrap.min.js"></script> <body class="bootstrap-admin-without-padding"> 池州学院 230312242 杨洪博 课设 <div style="background-image: url('image/2.png'); background-size: cover; background-repeat: no-repeat; background-position: center;"></div> <div class="col-lg-12"> <div class="alert alert-info"> <a class="close" data-dismiss="alert" href="#">×</a> 欢迎登录图书馆管理系统 </div> <form class="bootstrap-admin-login-form" method="post" action="/books/LoginServlet"> <% String state = (String)session.getAttribute("state"); session.removeAttribute("state"); if(state!=null){ %> <label class="control-label" for="username">密码错误</label> <%}%> <div class="form-group"> <label class="control-label" for="username">账 号</label> <input type="text" class="form-control" id="username" name="username" required="required" placeholder="学号"/> <label class="control-label" for="username" style="display:none;"></label> </div> <div class="form-group"> <label class="control-label" for="password">密 码</label> <input type="password" class="form-control" id="password" name="password" required="required" placeholder="密码"/> <label class="control-label" for="username" style="display:none;"></label> </div> <label class="control-label" for="password">没有账号请<a href="/books/register.jsp" style="color:blue;">注册</a></label> <br> <input type="submit" class="btn btn-lg btn-primary" value="登    录"/> </form> </div> </div> </div> <div class="modal fade" id="modal_info" tabindex="-1" role="dialog" aria-labelledby="addModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="infoModalLabel">提示</h4> </div> <div class="modal-body"> <div class="row"> <div class="col-lg-12" id="div_info"></div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" id="btn_info_close" data-dismiss="modal">关闭</button> </div> </div> </div> </div> </body> </html>文件路径没问题 但图片显示不出来
06-22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值