Session
作者:互联网
资料来自多年前的 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