今天在开发中遇到了,关于session的一个bug,现在就系统的总结一下相关的知识。
本文旨在帮助大家一次搞定,这是个什么东西。内容是由个人理解,搜集资料总结而成的。有问题可指出
如果你遇到了,在一次浏览器的“生命周期内”(以下提到。均为此意:打开浏览器关闭之前),取不到之前存在seesion里面的数据,这个问题,那么我们需要考虑的就是,在你取数据之前一定有“销毁session”的操作。因为,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;
知道了它是怎么创建的以后。使用就非常简单了。
存放
你可以这样放一些数据进去,value部分的类型可是object哦~ 你也可以直接这样:
获取
你也可以这样直接拿到你放进去的数据,当然一般是其他“地方”获取。 你也可以这样直接拿到此时seesion的唯一id标识。
1、到达web服务设定的Session过期时间。
2、web服务停止。
3、手动调用session对象的invalidate方法。
Session的创建和销毁可以通过HttpSessionListener来监听
你可以在session创建的时候,设置一些属性,也可以通过配置文件去设置。具体有哪些属性,以及属性有哪些含义,这里就不在赘述了
还有其他的一些也可以查看我以前总结的知识,也给自己留个直接访问链!
session、cookie、token的区别与联系