Session Implicit Object in JSP with examples

Session is most frequently used implicit object in JSP. The main usage of it to gain access to all the user’s data till the user session is active.

Methods of session Implicit Object

setAttribute(String, object) – This method is used to save an object in session by assigning a unique string to the object. Later, the object can be accessed from the session by using the same String till the session is active. setAttribute and getAttribute are the two most frequently used methods while dealing with session in JSP.

getAttribute(String name) – The object stored by setAttribute method is fetched from session using getAttribute method. For example if we need to access userid on every jsp page till the session is active then we should store the user-id in session using setAttribute method and can be accessed using getAttribute method whenever needed.

removeAttribute(String name) – The objects which are stored in session can be removed from session using this method. Pass the unique string identifier as removeAttribute’s method.

getAttributeNames – It returns all the objects stored in session. Basically, it results in an enumeration of objects.

getCreationTime – This method returns the session creation time, the time when session got initiated (became active).

isNew() – Used to check whether the session is new. It returns Boolean value (true or false). Mostly used to track whether the cookies are enabled on client side. If cookies are disabled the session.isNew() method would always return true.

invalidate() – It kills a session and breaks the association of session with all the stored objects.

The session.jsp page displays the name which user has entered in the index page and it stores the the same variable in the session object so that it can be fetched on any page until the session becomes inactive.

Comments

The latest version of Safari 5.1 and higher, the session value is always null. However, the same Safari browser is working fine in ‘Stand alone Server’. The site working all other browsers including IE. I have already reported the bugs to Apple. Any clue?