2 Minutes To Code (β Version)

JSP - 2 minute tutorial

Introduction to 'session' implicit object

Http is a stateless protocol. Which means if webserver receives multiple requests, http protocol provides no information about whether these requests have come from same clien tor different clients.

However, webservers have come up with the concept of session to solve this problem. Under the hood, sessions are maintained by using either cookies, url rewriting or hidden input form fields.

session is an instance of javax.servlet.http.HttpSession. Let's see a session is action below.
	<%= "Current session id = " + session.getId() %>

The above code will produce the following webpage :

The commonly used methods of session object are :

Method Description
Object getAttribute(String) Gets the object stored in session by given name
Enumeration getAttributeNames() Gets names of all objects stored in session
void setAttribute(String, Object) Stores the given object in session
void removeAttribute(String) Removes object from session
void invalidate() Kills current session, discards all data stored in it
Strig getId() Gets the system generated identifier of session
boolean isNew() Returns true if session is created by the current http request, returns false on subsequent requests from same client
void setMaxInactiveInterval(int) Sets validity period or time-to-live for session between successive requests in seconds
int getMaxInactiveInterval() Gets validity period or time-to-live of session between successive requests in seconds
long getCreationTime() Gets session creation timestamp in milliseconds elapsed since midnight January 1, 1970 GMT
long getLastAccessedTime() Gets timestamp of last http request from session's client in milliseconds elapsed since midnight January 1, 1970 GMT