以前看到书上session 的生命周期,知道session的生命周期是在第一次访(即打开浏览器输入地址成功访问)的时候被创建。同时HttpSessionListener接口的sessionCreate会被调用。
等到浏览器关闭或者服务器重启的时候session会被创建。
但在最近的实验中发现,在浏览器直接访问默认的servlet时,session并没有被创建出来。而当在servlet中执行 HttpSession session = request.getSession(); 时显示session被创建出来。
由此可见浏览器访问时session 并不是一定会被创建的。
查api可以发现这么一段:
getSession HttpSession getSession(boolean create) Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session. If create is false and the request has no valid HttpSession, this method returns null. To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown. Parameters:create - true to create a new session for this request if necessary; false to return null if there‘s no current sessionReturns:the HttpSession associated with this request or null if create is false and the request has no valid sessionSee Also:getSession() getSession HttpSession getSession() Returns the current session associated with this request, or if the request does not have a session, creates one. Returns:the HttpSession associated with this requestSee Also:getSession(boolean)
划横线部分是说如果create为false 并且request 内没有HttpSession 对象 ,此方法会返回null
说明session默认是不存在的,调用getsession()才会被创建。
时间: 2024-11-09 02:57:50