HTTP Session
Session is another technology to track the user activity. Unlike
the cookie which is client-based. It is server-based. Different Web servers
have different ways to implement the session, but in general, we can consider session
is a special memory area in the server to contain the user info. The server and set the key-value pair of for a
user and get the value by key for feature usage.
This blog will use Java Web Server as an example to show how
session is working.
Create/Get/Set Session.
In servlet, session can be got by
·
HttpSession session = request.getSession(true); //get the session
·
session.setAttribute(“logintime”, new Date()); //set session
attribute
·
out.println(“login time is” + (Date) session.getAttribute(“logintime”)); //get session attribute.
In JSP, session is a
hidden object and if not disable, you can use it without declaration.
·
session.setAttribute(“logintime”, new Date());
·
Date logintime = (Date) session.getAttribute(“logintime”);
Session lifecycle:
·
Session is created during the time when user
access a dynamic web page , any accessing to a static page won’t create an session.
·
When the user access the server, the server will
update the session last access time or re-activate it.
·
When the session is expired, it will be deleted
from the server side.
Session common methods: the names are self-explained.
setAttribute()
getAttribute()
getID()
getLastAccessedTime()
setMaxInteractiveInterval()
invalidate()
Compare between Session and Cookie
- Code: Cookie can only store the ASCII, encoded is needed to store other type of data. Session can store any data and even Java objects.
- Security/privacy: cookie is visible to the users and can be modified by malicious programes. Session is stored in the server and difficult to hack it.
- Expire date: cookie can set to be very long or even not expired. Session usually very short to keep the memory usage.
- Client requirement: cookie must be supported by the client. Like some mobile device, it does not support cookie.
No comments:
Post a Comment