---
title: "Cookie和Session解析"
author: "dubaopeng"
date: "2011-05-20T13:07:02Z"
tags: ["C", "C++", "Servlet", "应用服务器", "浏览器"]
categories: ["Web前端"]
slug: "cookie-session"
draft: false
lastmod: "2011-05-23T20:13:57Z"
id: 1051530
url: "https://dubaopeng.iteye.com/blog/1051530"
---

\[size=large]\[color=blue]1.关于Cookie, 在客户端浏览器保存用户状态的一种机制\[/color] \[/size] \[size=medium] servlet中的Cookie含有三个属性: name, value, maxAge maxAge = 60 表示：此cookie在客户端存在1分钟 两个特殊值： maxAge = -1 表示 : 此Cookie生命周期由保存它的浏览器决定 ，(浏览器开则生，关则死)，默认的 maxAge = 0 表示 : 删去以前的相应cookie存储 Cookie应用实例 : \[/size] \[code="java"] package com.kettas.servlet ; import javax.servlet.\*; import javax.servlet.http.\*; import java.io.\*; public class CookieServlet extends HttpServlet{ @Override public void service( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException {// 创建一个新的Cookie对象, 构造参数分别为Cookie的name和value属性 Cookie c = new Cookie( "test" , "1234567890" ); // 将Cookie对象加入response中，这样才能被带入客户端 response.addCookie( c ) ; // 从请求中获取客户端Cookie数组 Cookie\[] cookies = request.getCookies(); response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); out.println(""); out.println( "" ) ; out.println( "

# Cookie List

* * *

" ) ; if( cookies != null ){ for( Cookie cookie : cookies ) { out.println( "

## " + cookie.getName() + "=" + cookie.getValue() + "

" ) ; } }else{ out.println( "

## No cookie

" ) ; } out.println( "" ) ; out.println(""); out.flush(); } } \[/code]\[size=large]\[color=blue] 2. 关于HttpSession, 在服务器端保存用户状态的一种机制 \[/color]\[/size] \[size=medium](1) 获取HttpSession对象的方法 : // 参数为true，表示若存在对应的HttpSession对象，则返回。若不存在，则创建一个新的。 // 若参数为false，表示若存在对应的HttpSession对象，则返回。若不存在，则返回null。 HttpSession session = request.getSession(true); (2) 对HttpSession对象, 进行存取数据的操作 // 两个参数，分别为命名属性和对应的数据 session.setAttribute("name", data); // 一个参数，命名属性，注意返回的为Object对象，要强转 session.getAttribute("name"); (3) 比较Session和request : request : 创建 : 当用户请求到达服务器的时候 销毁 : 当本次请求的应答回到客户端的时候. 客户端的一次请求应答之间 session : 创建 : 当用户第一次调用request.getSession( true ) 销毁 : 超时 ( 两级超时限制 ) 1) 内存 ---&gt; 文件 . 2) 从文件系统销毁 . session的原理 : 给每个浏览器一个cookie，这个cookie的name属性为"jsessionid"，value属性为这个session 对应的ID值。 (4) 当浏览器拒绝cookie时可以用URL把session的id提交给服务器 如 : http://localhost:8989/servletapp/forwardB;jsessionid=37D50D093CCD4A37CC1118785E38F438 "url;jessionid="+ session.getId() response.encodeURL("url") ：对url进行编码\[/size]