体验

  使用HttpSession进行会话管理,完全可以忽略HTTP无状态的事实。


HttpSession会话管理原理

  使用HttpSession进行会话管理十分方便,让Web应用程序看似可以“记得”浏览器发出的请求,连接数个请求间的关系。但无论如何,Web应用程序基于HTTP协议的事实并没有改变。这背后Web容器帮我们做了一些工作。
  当第一次调用HttpServletRequest的getSession()时,Web容器会创建一个HttpSession对象,每个HttpSession对象都有个特殊的ID,这个Session ID默认会使用Cookie存放在浏览器中。当浏览器再次请求应用程序时,会将Cookie中存放的Session ID一并发送给应用程序,Web容器就能根据Session ID来找出对应的HttpSession对象,这样就可以取得各个浏览器的会话数据。


存储Session ID的cookie

  存储Session ID的Cookie “默认”为关闭浏览器就失效,所以重启浏览器请求应用程序时,通过getSession()取得的是新的HttpSession对象。注意默认关闭浏览器马上失效的是浏览器上的Cookie,而不是HttpSession。因为Cookie失效了,就无法通过Cookie来发送Session ID,所以使用getSession()时,容器会产生新的HttpSession。


HttpSession

  要让HttpSession立即失效必须运行invalidate()方法,否则的话,HttpSession会等到设定的失效期间过后才会被容器销毁回收。
  可以执行HttpSession的setMaxInactiveInterval()方法,设定浏览器多久没有请求应用程序,HttpSession就自动失效,单位是“秒”。也可以在web.xml中设定HttpSession默认的失效时间,单位是“分钟”。


新接口

  在Servlet 3.0中新增了SessionCookieConfig接口,可以通过ServletContext的getSessionCookieConfig()来取得实现该接口的对象,通过该对象可以设定存储Session ID的Cookie的相关信息,例如可以通过setName()将默认的名称(在Tomcat中,Cookie的默认名称是JSESSIONID)修改为别的名称,通过setAge()设定存储Session ID的Cookie存活期限等,单位是“秒”。
  但是注意,设定SessionCookieConfig必须在ServletContext初始化之前,所以实际上修改存储Session ID的Cookie存活期限等信息时有两种方法:
  1、在web.xml中设定
  2、实现ServletContextListener,容器在初始化ServletContext时会调用ServletContextListener的contextInitialized()方法,可以在其中取得ServletContext进行SessionCookieConfig设定。


占用内存

  HttpSession对象会占用服务器内存空间,所以HttpSession中尽量不要存储耗资源的大型对象,必要时将属性移除,或者不需使用HttpSession时,执行invalidate()让HttpSession失效。


线程安全
  HttpSession并非线程安全,所以必须注意属性设定时共享存取的问题。


example

package com.test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter; @WebServlet("/questionnaire")
public class Questionnaire extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<meta charset='UTF-8'>");
out.println("<title>问卷调查</title>");
out.println("</head>");
out.println("<body>"); String page = request.getParameter("page");
out.println("<form action='questionnaire' method='get'>"); if(page == null) { // 第一頁問卷
out.println("問題一:<input type='text' name='p1q1'><br>");
out.println("問題二:<input type='text' name='p1q2'><br>");
out.println("<input type='submit' name='page' value='page2'>");
}
else if("page2".equals(page)) { // 第二頁問卷
HttpSession session = request.getSession();
session.setAttribute("p1q1", request.getParameter("p1q1"));
session.setAttribute("p1q2", request.getParameter("p1q2"));
//session.invalidate(); // 销毁session
out.println("問題三:<input type='text' name='p2q1'><br>");
out.println("<input type='submit' name='page' value='finish'>");
}
else if("finish".equals(page)) { // 最後答案收集
HttpSession session = request.getSession();
out.println(session.getAttribute("p1q1") + "<br>");
out.println(session.getAttribute("p1q2") + "<br>");
out.println(request.getParameter("p2q1") + "<br>");
}
out.println("</form>");
out.println("</body>");
out.println("</html>");
out.close();
} @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

<?xml version="1.1" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name> <session-config>
<session-timeout>30</session-timeout>
<cookie-config>
<name>my-session-id</name>
<!-- js 无法读取cookie -->
<http-only>true</http-only>
<!-- 单位是秒 -->
<!--<max-age>50</max-age>-->
</cookie-config>
</session-config> </web-app>
测试方法:
1、测试关闭浏览器cookie失效,原来的session对象无法找到
    (1)访问:http://127.0.0.1:8000/questionnaire
    (2)填写表单并提交,提交后服务器端会往session写入数据
    (3)关闭浏览器
    (4)访问:http://127.0.0.1:8000/questionnaire?p2q1=123&page=finish
2、SessionCookieConfig测试
    查看web.xml

HttpSession implements session的更多相关文章

  1. url override and HttpSession implements session for real

    无论cookie有没有禁用,HttpSession都有效 package com.test; import javax.servlet.ServletException; import javax.s ...

  2. url override and HttpSession implements session for form

    url 重写结合HttpSession实现会话管理之 form 提交 package com.test; import javax.servlet.ServletException; import j ...

  3. url override and HttpSession implements session

    背景 HttpSession默认使用Cookie存储Session ID,如果在用户禁用浏览器Cookie的功能后,仍打算运用HttpSession来进行会话管理,那么可以搭配URL重写来实现. 实现 ...

  4. url override implements session

    url 重写实现会话概述 URL重写是对GET请求参数的应用,当服务器响应浏览器上一次请求时,将某些相关信息以超链接方式响应给浏览器,超链接中包括请求参数信息. 特点:URL必须以GET方式发送请求. ...

  5. cookie implements session

    cookie实现会话 服务器调用response.addCookie()设置set-cookie响应头后,浏览器收到这个响应头与数值后,会将它以文件的形式存储于本地PC上.当浏览器再次访问同一Web服 ...

  6. hidden field implements session

    隐藏域实现会话管理概述 如果你正在制作一个网络问卷,由于问卷内容很长,因此必须分几个页面,上一页面作答完后,必须请求服务器显示下一个页面. 但是在HTTP协议中,服务器并不会记得上一次请求的状态.既然 ...

  7. HttpSession与Hibernate中Session的区别

    一.javax.servlet.http.HttpSession是一个抽象接口 它的产生:J2EE的Web程序在运行的时候,会给每一个新的访问者建立一个HttpSession,这个Session是用户 ...

  8. HttpSession and Hibernate session

    一.javax.servlet.http.HttpSession是一个抽象接口   它的产生:J2EE的Web程序在运行的时候,会给每一个新的访问者建立一个HttpSession,这个Session是 ...

  9. session 机制和 httpsession 详解 (转载)

    https://www.cnblogs.com/bjanzhuo/archive/2013/02/27/3575884.html 一.术语session 在我的经验里,session这个词被滥用的程度 ...

随机推荐

  1. CSS3 :nth-child(n)使用注意

    :nth-child(n)    ---->选中某个元素,该元素必须是某个父元素下的第n个子元素: p:nth-child(n)   ---->选中p元素,且该p元素必须是某个父元素下的第 ...

  2. (转)DB2 HADR 监控详解

    原文:https://www.ibm.com/developerworks/cn/data/library/techarticles/dm-1010baosf/ HADR 简介 HADR( 高可用性灾 ...

  3. python中如何使输出不换行

    1.在python 2.x版本中,使用“,”(不含双引号)可使输出不换行,例如 2.python 3.x版本输出不换行格式如下 print(x, end="")    end=&q ...

  4. [转]asp.net core中的View Component

    解读ASP.NET 5 & MVC6系列(14):View Component http://www.cnblogs.com/TomXu/p/4496486.html

  5. 你误解了Windows的文件后缀名吗?

    一.背景说明 有很多的小伙伴对windows下的文件后缀名不能很好地理解作用和区别,更不用说高深的使用了,在这里给大家说一下这些文件后缀名到底有什么区别,有什么作用呢? 二.说明 简单的说来,wind ...

  6. es6中let,const区别与其用法

    ECMAScript 是什么? 首先,我们都知道JavaScript由三部分组成:ECMAScript,DOM,BOM: 其中的ECMAScript是Javascript的语法规范. ECMAScri ...

  7. tomcat 日志详解

    1 tomcat  日志详解 1.1  tomcat 日志配置文件 tomcat 对应日志的配置文件:tomcat目录下的/conf/logging.properties. tomcat 的日志等级有 ...

  8. Python 日期时间处理模块学习笔记

    来自:标点符的<Python 日期时间处理模块学习笔记> Python的时间处理模块在日常的使用中用的不是非常的多,但是使用的时候基本上都是要查资料,还是有些麻烦的,梳理下,便于以后方便的 ...

  9. Mahout实战---评估推荐程序

    推荐程序的一般评测标准有MAE(平均绝对误差),Precision(查准率),recall(查全率) 针对Mahout实战---运行第一个推荐引擎 的推荐程序,将使用上面三个标准分别测量 MAE(平均 ...

  10. Nodejs学习笔记(一)—简介及安装Node.js开发环境

    一.简介 Node.js是让Javascript脱离浏览器运行在服务器的一个平台,不是语言: Node.js采用的Javascript引擎是来自Google Chrome的V8:运行在浏览器外不用考虑 ...