标签:getSession request 会话 Session 超时 response
资料来自多年前的 B站
Session会话
什么是Session会话?
- Session 会话是一个接口。
- Session 是一个域对象。
- Session 是用来维护客户端和服务器之间关联的一种技术。
- 一个Session会话对象维护一个客户端和服务器之间的关联
- 我们经常把用户登录的信息保存到Session域中。
Cookie是把用户的信息(程序需要的信息)保存到客户端。
Session是把用户的信息(程序需要的信息)保存到服务器。
- 如何创建Session和获取(id号,是否为新)
- 如何创建Session会话对象 =====>>>>> request.getSession()
- 如何获取Session会话对象 =====>>>>> request.getSession()
第一次调用request.getSession()是创建。
之后调用request.getSession()都是获取。
isNew()判断当前Session会话对象是否是刚创建的会话。
返回true。表示刚创建
返回false。表示获取的。
Session会话有一个属性是id。可以唯一的区别每一个会话。
如何获取Session会话的id ======>>>>> session.getId();
Session域数据的存取
protected void setAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 随机生成一个int数据,然后保存到Session中。 Integer num = random.nextInt(100); request.getSession().setAttribute("num", num); response.getWriter().write("服务器给你随机生成的数是:" + num); } protected void getAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object object = request.getSession().getAttribute("num"); response.getWriter().write("获取到你刚刚保存的数据是:" + object); }
Session生命周期控制
getMaxInactiveInterval(); 获取当前Session的超时时间。
Tomcat服务器默认的Session超时时间为30分钟。在tomcat服务器的配置文件web.xml中早有如下的配置:
以下配置,影响了所有运行在此Tomcat服务器上的所有web工程,创建的所有Session对象。
<!-- ==================== Default Session Configuration ================= --> <!-- You can set the default session timeout (in minutes) for all newly --> <!-- created sessions by modifying the value below. --> <session-config> <session-timeout>30</session-timeout> </session-config>
如果你想对自己的web工程,单独的设置Session的超时时间。那么可以在你的web工程的web.xml配置文件中进行如下的配置:
<!-- 单独设置你的web工程。所有Session默认的超时时间为20分钟 --> <session-config> <session-timeout>20</session-timeout> </session-config>
能不能对单个Session进行单独的设置超时时间。可以!!!
可以通过 setMaxInactiveInterval( int second ); 来设置当前Session的超时时间
Session的超时指的是,客户端和服务器之间两次请求的间隔时长。
Session超时图解:
protected void life3(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 当前Session3秒后超时(超时之后Session就不可用,只能创建新的。) request.getSession().setMaxInactiveInterval(3); response.getWriter().write("Session已经被设置为3秒后超时"); }
如何让一个Session马上无效(超时或销毁) =======>>>>>> invalidate()
protected void deleteNow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // session就无效 。保存在里面的数据,也跟着销毁了 request.getSession().invalidate(); response.getWriter().write("当前Session已经被销毁!!!"); }
浏览器和服务器Session之间关联的技术内幕:
Session之所以能够解决客户端和服务器之间关联。是通过Cookie技术来实现的。
这个Cookie默认的存活时间为Session。也就是浏览器关闭Cookie就会被删除。
标签:getSession,request,会话,Session,超时,response 来源: https://www.cnblogs.com/Alay/p/15165507.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。