Here’s how you get a session ID from the request:
HttpSession session = request.getSession();
Here’s what this does for you:
If the session includes a session ID cookie
then find the session matching that session ID
else (no session ID cookie or no matching session )
create a new session
(如果浏览器第一次登陆,则request.getSession()会去创建一个新的HttpSession对象。服务端是如何判断浏览器第一登陆的呢? 就是看下请求报文中有没有JSESSION字段。如果有,还不能判断就一定是非第一次登陆,因为浏览器不一定按规矩出牌,甚至JSESSION对应的cookie有些浏览器是允许用户事先配好的。所以,非第一次访问的条件是“请求中带有JSESSION,而且该JSESSION的号码ID的确是服务器生成的 ,而且在服务端还没有过期。”。所以,一般JSESSION的号码应该要弄成不容易被猜出来。)
==Java’s session tracking API, II
Here’s how you send a cookie in the response:
HttpSession session = request.getSession();
What this does for you:
1、Creates a new HttpSession object, or retrieves a previous one
2、Creates a unique session ID (在服务端保存在HttpSessionContext中,是个从ID到HttpSession的映射。)
3、Makes a new cookie object
Associates the cookie with the session ID (HttpSession的ID要依靠cookie传递给客户端)
Puts the cookie in the response (under the Set-Cookie header)
Notice that:
This is exactly the same call as in the previous slide
The message is sent to the request, not the response
==Using an HttpSession
session.setAttribute(String name, Object value)
You can save objects in an HttpSession
object = session.getAttribute(String name)
You can retrieve your saved objects by name
Enumeration e = session.getAttributeNames()
You can find the names of all your objects
session.removeAttribute(String name)
You can get rid of an object you no longer need
boolean session.isNew()
true if the session is newly created, rather than retrieved
String id = session.getId()
You can get the session ID (if you’re debugging, or just curious)
==Quitting an HttpSession
session.invalidate()
Quits the session and unbinds any objects in it
milliseconds = session.getCreationTime()
(since midnight January 1, 1970 GMT)
milliseconds = session.getLastAccessedTime()
(again, since 1970)
session.setMaxInactiveInterval(int seconds) (最大非活动间隔)
Sets the time until the session is automatically invalidated
int seconds = session.getMaxInactiveInterval()
So the Session API does nearly everything you need!