Java会话主要分为两块:Cookie和HttpSession
Cookie技术:会话数据保存在浏览器客户端。
Session技术:会话数据保存在服务器端。
一.下面介绍一下Cookie的应用
1. Cookie技术核心
Cookie类:用于存储会话数据
1)构造Cookie对象
Cookie(java.lang.String name, java.lang.String value)
2)设置cookie
void setPath(java.lang.String uri) :设置cookie的有效访问路径
void setMaxAge(int expiry) : 设置cookie的有效时间
void setValue(java.lang.String newValue) :设置cookie的值
3)发送cookie到浏览器端保存
void response.addCookie(Cookie cookie) : 发送cookie
4)服务器接收cookie
Cookie[] request.getCookies() : 接收cookie
2. Cookie原理
1)服务器创建cookie对象,把会话数据存储到cookie对象中。
new Cookie("name","value");
2)服务器发送cookie信息到浏览器
response.addCookie(cookie);
举例: set-cookie: name=eric (隐藏发送了一个set-cookie名称的响应头)
3)浏览器得到服务器发送的cookie,然后保存在浏览器端。
4)浏览器在下次访问服务器时,会带着cookie信息
举例: cookie: name=eric (隐藏带着一个叫cookie名称的请求头)
5)服务器接收到浏览器带来的cookie信息
request.getCookies();
3 Cookie的细节
1)void setPath(java.lang.String uri) :设置cookie的有效访问路径。有效路径指的是cookie的有效路径保存在哪里,那么浏览器在有效路径下访问服务器时就会带着cookie信息,否则不带cookie信息。
2)void setMaxAge(int expiry) : 设置cookie的有效时间。
正整数:表示cookie数据保存浏览器的缓存目录(硬盘中),数值表示保存的时间。
负整数:表示cookie数据保存浏览器的内存中。浏览器关闭cookie就丢失了!!
零:表示删除同名的cookie数据
3)Cookie数据类型只能保存非中文字符串类型的。可以保存多个cookie,但是浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie,每个Cookie的大小限制为4KB。
4.下面是Cookie应用的代码
1)设置Cookie
1 packagecom.vastsum;2
3 importjava.io.IOException;4 importjavax.servlet.ServletException;5 importjavax.servlet.annotation.WebServlet;6 importjavax.servlet.http.Cookie;7 importjavax.servlet.http.HttpServlet;8 importjavax.servlet.http.HttpServletRequest;9 importjavax.servlet.http.HttpServletResponse;10
11 /**
12 * Servlet implementation class CookieDemo13 */
14 @WebServlet("/CookieDemo")15 public class CookieDemo extendsHttpServlet {16
17 protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {18 //创建Cookie对象
19 Cookie cookie = new Cookie("name","shutu008");20 /**
21 * 如果没有设置路径,表示当前项目根目录下22 * 如果设置路径保存在指定目录下23 */
24 //设置保存在 /test目录下,设置Cookie对象的路径,如果设置表示此Cookie不在根目录下。
25 cookie.setPath("/test");26 //设置cookie时间,默认时间粒度为秒
27 cookie.setMaxAge(1000);28 //将Cookie对象发送到浏览器
29 response.addCookie(cookie);30
31 }32
33
34 }
2)获取cookie
1 packagecom.vastsum;2
3 importjava.io.IOException;4 importjavax.servlet.ServletException;5 importjavax.servlet.annotation.WebServlet;6 importjavax.servlet.http.Cookie;7 importjavax.servlet.http.HttpServlet;8 importjavax.servlet.http.HttpServletRequest;9 importjavax.servlet.http.HttpServletResponse;10
11 /**
12 * Servlet implementation class CookieTest13 */
14 @WebServlet("/CookieTest")15 public class CookieTest extendsHttpServlet {16 private static final long serialVersionUID = 1L;17
18 /**
19 *@seeHttpServlet#HttpServlet()20 */
21 publicCookieTest() {22 super();23 //TODO Auto-generated constructor stub
24 }25
26 /**
27 *@seeHttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)28 */
29 protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {30
31 //将Cookie对象存储到数组中
32 Cookie[] cookies =request.getCookies();33 if (cookies!=null){34 //遍历所有Cookie对象
35 for(Cookie c:cookies){36 //获取Cookie对象的名称
37 String name =c.getName();38 //获取Cookie对象的值
39 String value =c.getValue();40 //将结果输出到页面上
41 response.getWriter().write(name+ "=" +value);42 }43 }44 }45
46 }
二.接下来介绍一下session的应用
1.HttpSession类:用于保存会话数据
1)创建或得到session对象
HttpSession getSession()
HttpSession getSession(boolean create)
2)设置session对象
void setMaxInactiveInterval(int interval) : 设置session的有效时间
void invalidate() : 销毁session对象
java.lang.String getId() : 得到session编号
3)保存会话数据到session对象
void setAttribute(java.lang.String name, java.lang.Object value) : 保存数据
java.lang.Object getAttribute(java.lang.String name) : 获取数据
void removeAttribute(java.lang.String name) : 清除数据
2.Session原理
问题: 服务器能够识别不同的浏览者!!!
前提: 在哪个session域对象保存数据,就必须从哪个域对象取出!!!!
浏览器1:(给s1分配一个唯一的标记:s001,把s001发送给浏览器)
1)创建session对象,保存会话数据
HttpSession session = request.getSession(); --保存会话数据 s1
浏览器1的新窗口(带着s001的标记到服务器查询,s001->s1,返回s1)
1)得到session对象的会话数据
HttpSession session = request.getSession(); --可以取出 s1
新的浏览器1:(没有带s001,不能返回s1)
1)得到session对象的会话数据
HttpSession session = request.getSession(); --不可以取出 s2
浏览器2:(没有带s001,不能返回s1)
1)得到session对象的会话数据
HttpSession session = request.getSession(); --不可以取出 s3
3. Sesson细节
1)java.lang.String getId() : 得到session编号
2)两个getSession方法:
getSession(true) / getSession() : 创建或得到session对象。没有匹配的session编号,自动创建新的session对象。
getSession(false): 得到session对象。没有匹配的session编号,返回null
3)void setMaxInactiveInterval(int interval) : 设置session的有效时间
session对象销毁时间:
3.1 默认情况30分服务器自动回收
3.2 修改session回收时间
3.3 全局修改session有效时间
1
手动销毁session对象
void invalidate() : 销毁session对象
4)如何避免浏览器的JSESSIONID的cookie随着浏览器关闭而丢失的问题
/**
* 手动发送一个硬盘保存的cookie给浏览器
*/
Cookie c = new Cookie("JSESSIONID",session.getId());
c.setMaxAge(60*60);
response.addCookie(c);
4.下面是HttpSession应用的代码
1 packagecom.vastsum;2
3 importjava.io.IOException;4 importjava.util.Enumeration;5
6 importjavax.servlet.ServletException;7 importjavax.servlet.annotation.WebServlet;8 importjavax.servlet.http.HttpServlet;9 importjavax.servlet.http.HttpServletRequest;10 importjavax.servlet.http.HttpServletResponse;11 importjavax.servlet.http.HttpSession;12
13 /**
14 * Servlet implementation class HttpSessionDemo15 */
16 @WebServlet("/HttpSessionDemo")17 public class HttpSessionDemo extendsHttpServlet {18 private static final long serialVersionUID = 1L;19
20 /**
21 *@seeHttpServlet#HttpServlet()22 */
23 publicHttpSessionDemo() {24 super();25 //TODO Auto-generated constructor stub
26 }27
28 /**
29 *@seeHttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)30 */
31 protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {32 //TODO Auto-generated method stub33 //设置编码
34 response.setContentType("text/html;charset=UTF-8");35 //创建HttpSession对象
36 HttpSession httpSession =request.getSession();37 //设置HttpSession的值和内容
38 httpSession.setAttribute("name", "srv");39 httpSession.setAttribute("phone", "051112345678");40 //获取唯一的session id
41 String sessionId =httpSession.getId();42 //获取指定名称的值43 //String value = (String)httpSession.getAttribute("name");
44
45 /**
46 * 获取HttpSession中所有的值。返回值是枚举类型47 */
48 Enumeration attributeNames =httpSession.getAttributeNames();49
50 while(attributeNames.hasMoreElements()){51 //遍历出session中所有的name
52 String name =(String)attributeNames.nextElement();53 //找出name对应的value
54 String value =(String)httpSession.getAttribute(name);55 //输出到浏览器
56 response.getWriter().write(name+ "=" +value);57 }58 if(httpSession.isNew()){59 response.getWriter().write("session不存在,最新sessionId是:" +sessionId);60 }61 else{62 response.getWriter().write("session已经存在,设置的sessionId是:" +sessionId );63 }64 //设置对象销毁时间,时间粒度为分钟
65 httpSession.setMaxInactiveInterval(1);66 }67
68 }