会话跟踪技术之——cookie

Posted 初夏的一棵歪脖子树

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了会话跟踪技术之——cookie相关的知识,希望对你有一定的参考价值。

1.cookieForm

技术分享
 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10 <form action="setCookie.jsp" method="post">
11 网名:<input type="text" name="webName"/><br/>
12 网址:<input type="url" name="url"/><br/>
13 <button type="submit">提交</button>
14 </form>
15 </body>
16 </html>
View Code

2.setCookie

技术分享
 1 <%@page import="java.net.URLEncoder"%>
 2 <%@ page language="java" contentType="text/html; charset=UTF-8"
 3     pageEncoding="UTF-8"%>
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>Insert title here</title>
 9 </head>
10 <body>
11 <%
12 //获取从表单提交过来的数据,作为cookie的对象
13  String webName=request.getParameter("webName");
14  String url=request.getParameter("url");
15  //解决表单传到另一个页面乱码问题
16  webName=new String(webName.getBytes("ISO-8859-1"),"utf-8");
17  
18  //分别创建两个cookie对象
19  Cookie cookie1=new Cookie("name",URLEncoder.encode(request.getParameter("webName"),"utf-8"));
20  Cookie cookie2=new Cookie("url",url);
21  
22  //分别设置Cookie的有限期
23  cookie1.setMaxAge(3*3600);//设置3小时
24  cookie2.setMaxAge(300);
25  
26  //在响应头部添加Cookie
27  response.addCookie(cookie1);
28  response.addCookie(cookie2);
29 %>
30 </body>
31 </html>
View Code

3.getCookie

技术分享
 1 <%@page import="java.net.URLDecoder"%>
 2 <%@ page language="java" contentType="text/html; charset=UTF-8"
 3     pageEncoding="UTF-8"%>
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>Insert title here</title>
 9 </head>
10 <body>
11 <%
12 Cookie[] cookie=request.getCookies();
13 if(cookie.length>0)
14 {
15     for(int i=0;i<cookie.length;i++)
16     {
17         String name=cookie[i].getName();
18         String value=cookie[i].getValue();
19         /* //查找某个cookie来删除
20         if(name.equalsIgnoreCase("name"))
21         {
22             cookie[i].setMaxAge(0);
23             response.addCookie(cookie[i]);
24         } */
25         //如果value的值出现乱码,则要进行解码
26         value=URLDecoder.decode(value, "utf-8");
27         out.print(name+"<br/>");
28         out.print(value);
29     
30     }
31     
32 }
33 
34 %>
35 </body>
36 </html>
View Code

 

以上是关于会话跟踪技术之——cookie的主要内容,如果未能解决你的问题,请参考以下文章

Django之cookie与session

07.会话跟踪技术cookie与session

Django之cookie 与session组件

04-cookies 会话跟踪技术

Django - cookies 会话跟踪技术

客户端会话跟踪技术 Cookie 浅谈