一次弄明白Seeesion!
今天在开发中遇到了,关于session的一个bug,现在就系统的总结一下相关的知识。
本文旨在帮助大家一次搞定,这是个什么东西。内容是由个人理解,搜集资料总结而成的。有问题可指出
session
1、session是什么?
- 服务器可以为每个用户浏览器创建一个会话对象(session对象),浏览器在开启状态只能产生一个session(除非他销毁再生成。就算销毁在生成,此时生成的也是当前浏览器唯一的。),当新建一个窗口访问服务器时,还是原来的那个session。session中默认保存的是当前用户的信息。因此,在需要保存其他用户数据时,我们可以自己给session添加属性。session(会话)可以看为是一种标识,通过带session的请求,可以让服务器知道是谁在请求数据。
如果你遇到了,在一次浏览器的“生命周期内”(以下提到。均为此意:打开浏览器关闭之前),取不到之前存在seesion里面的数据,这个问题,那么我们需要考虑的就是,在你取数据之前一定有“销毁session”的操作。因为,session虽说是“唯一”的,但并不是不可变的。
2、session的创建
session是由服务器(浏览器)创建的,并保存在服务器上的。在session创建好之后,会把sessionId放在cookie中返回(response)给客户端。返回的cookie是保存在客户端的。
具体的代码实现在接口 HttpServletRequest 中这个接口有很多方法、
比如:这些方法的作用在注释中已经描述的相当清楚了
/**
* Returns an array containing all of the <code>Cookie</code> objects the
* client sent with this request. This method returns <code>null</code> if
* no cookies were sent.
*
* @return an array of all the <code>Cookies</code> included with this
* request, or <code>null</code> if the request has no cookies
*/
public Cookie[] getCookies();
/**
* Reconstructs the URL the client used to make the request. The returned
* URL contains a protocol, server name, port number, and server path, but
* it does not include query string parameters.
* <p>
* Because this method returns a <code>StringBuffer</code>, not a string,
* you can modify the URL easily, for example, to append query parameters.
* <p>
* This method is useful for creating redirect messages and for reporting
* errors.
*
* @return a <code>StringBuffer</code> object containing the reconstructed
* URL
*/
public StringBuffer getRequestURL();
而我们我么今天要谈的是 getSession()
这个方法,这个方法有一个重载方法getSession(boolean create)
他们都有各自的实现类。
这里我简单总结下。getSession(boolean create)
,这个方法的意思是create为true是时候,存在session就返回,不存在就创建,create为false时,存在返回,不存在返回null。具体的实现可以通过ide直接点进去查看。
而且getsession()
也是调用的getSession(boolean create)
只不过是直接赋值为true;
3、session的简单使用
知道了它是怎么创建的以后。使用就非常简单了。
存放
你可以这样放一些数据进去,value部分的类型可是object哦~
你也可以直接这样:
获取
你也可以这样直接拿到你放进去的数据,当然一般是其他“地方”获取。
你也可以这样直接拿到此时seesion的唯一id标识。
4、session的销毁时机
1、到达web服务设定的Session过期时间。
2、web服务停止。
3、手动调用session对象的invalidate方法。
Session的创建和销毁可以通过HttpSessionListener来监听
5、其他
你可以在session创建的时候,设置一些属性,也可以通过配置文件去设置。具体有哪些属性,以及属性有哪些含义,这里就不在赘述了
还有其他的一些也可以查看我以前总结的知识,也给自己留个直接访问链!
session、cookie、token的区别与联系
还没有评论,来说两句吧...