Session object is medium to interact with client and server. Session is a connection between user and server, involving exchange of information between user’s computer and server. Server knows information about each other by these session object. Web server put information of user in session object and whenever it needs information gets it from these session objects. This session object stores information in key value pair, just like hashtable. Today programming without session cannot thinkable. Most of web application is user based, somewhat use transaction (credit card, database transaction), shopping cart, email, and this needs session. Web server should know who is doing this transaction. This session object helps to differentiate users with each other, and increase application’s security. Every user have unique session, server exchange information with session objects until it get expired or destroyed by web server.
When JSP Session use
Mostly session is work with user base application, when login screen is used then set session if login is successful. It set for maximum time provided by web server or defined by application.
When JSP Session destroys
When user has done their work and want to close browser, it should be expire or destroy forcefully by user, ensure no other person can use his session.
JSP Store and Retrieve Session Variables
JSP Example of Creating session and retrieving session
<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<form name="frm" method="get" action="sessionSetRetrieve.jsp">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<td width="22%"> </td>
<td width="78%"> </td>
<td>Session value Set </td>
<td><input type="text" name="sessionVariable" /></td>
<td><input type="submit" name="submit" value="Submit"></td>
<%@ page language="java" import="java.util.*"%>
/// String getSessionValue= (String)session.getAttribute("sessionSet");
//this is use for session value in String data
<title>Cookie Create Example</title>
Session : <%=(String)session.getAttribute("MySession")%>
session.setAttribute("MySession",sessionSet) this is use to set new session variable. If we need to retrieve session variable, have to use session.getAttribute. In this we have to get it by session variable name here we are using MySession is session variable as key.
session.setMaxInactiveInterval(2700), this use to set maximum session time. 2700 is time in number. In this period, if user don’t do anything session get expired automatically.
Remove JSP Session Variables or Expire JSP Session
When session is no long needed, should be removed forcefully by user. This can be done by calling session method of invalidate method
This method expires session for current user, who request for log out.
New session can be find by isNew() method of session, when first time session is created, that is new session.