by Dinesh Thakur Category: Session

HttpSession object allocates memory on the server and remembers client data across the multiple requests in the form of session attribute values. HttpSession object is one per browser window (client) so each HttpSession object can be used to remember client data during a session.

HttpSession object means it is the object of a servlet container supplied Java class implementing javax.servlet.http.HttpSession interface. Every HttpSession object contains session id and this session id goes to browser window from web application and comes back to web application from browser window in the form of in memory cookie value. So, this technique is calledHttpSession with cookies technique.

(1)Browser window bl launches personal.html (form1) and sends the request to Srv1 of      CookieAppl application.

(2)Srv1 reads form1 data or request data.

(3)Srv1 creates HttpSession object on server for browser window b1 and writesform1/request1 data to that session object as session attribute values.

(4)Srv1 generates form2 as dynamic form page and sends the session id of HttpSession object to browser window as in memory cookie value.

(5)The in memory cookie having session id of HttpSession object (b1) allocate memory on the browser window. That cookie also remembers its web application name CookieAppl.

(6)End user fills up the form page (form2) and sends the request2 to Srv2 of CookieAppl. Along with this request session id will go to cookie values.

(7)Srv2 reads from2 data.

(8)Srv2 uses the session id read from the cookie to get access to the HttpSession object of browser window b1 and writes form2/request2 data to Ithat HttpSession object as session attribute values.

(9)Srv2 generates form3 as dynamic form page.

(10)Form3 generates request to Srv3. Along with this request session id will go to Srv3 as cookie value.

(11)Srv3 reads form3 data and session id from the cookie.

(12)Srv3 uses session id collected from the cookie to get access the HttpSession object of browser window b1 and reads forml/request1, form2/request2 data from the session attributes of that HttpSession attributes. This indicates that Srv3 is able to use request1/form1 data and request2/form2 data while processing form3 request/request3. This is nothing but session tracking.

(13)Srv3 writes form1, form2, form3 values to the database table as a record.

(14)Srv3 generates dynamic webpage having conformation message.

     

     When HttpSession object is created the session id of that session object automatically goes to the browser window as in memory cookie value. In HttpSession with cookies session tracing technique based application, the browser window (client) will be identify the multiple requests during a session based on the session id sent by the browser window along with the request. Session API(working withjavax.servlet.http.httpsession interface)

To create/locate httpsession object

(a) Httpsession ses=req.getSession();

• This method creates new httpsession object on server for browser window if httpsession object is not already available for browser window otherwise this method provides access to existing httpsession object of that browser window.

• This method can create the new session between browser window and web application if session is not already between them otherwise this method makes current request to join in the existing session.

• If this method is called in the firstservlet program of above diagram on the previous page then it makes request1 of browser window b1 beginning new session between browser window b1 and web application session App. If the same method is called secondservlet and thirdservlet then, it makes request2, request3 of browser window b1 participating in existing session.

(b) Http ses=req.getSession(false);

• This method gives access to existing httpsession object of browser window, if not available this method returns null(indicating new httpsession object cannot be created).

• When this method is called, the request can always join in existing session but Cannot create new session between browser window and web application.

• In the diagram, it is recommended to call req.getsession() in firstservlet to start the session and it is recommended to call req.getsession(false) method in secondservlet and thirdservlet to make them participate in the existing session.

(c) HttpSession ses=req.getSession();

     "same as (a)"

Conclusion:To create new session/to locate existing session use (a),(c) options only to locate existing session use (b) option.

To know session ID

String id=ses.getid();

To know session object creation time/session started time

longms=ses.getCreationTime() ;

Date d1= new Date(ms);

• In the above code ms represents milli seconds that have elapsed since1970 Jan 1st00:00 hours to date and the time of httpsession object creation in Epoch standard.

To know the last accessed time of httpsession object

   longms=ses.getlastaccessedtime() ;

   Date d2=new Date(ms);

• The above code gives the last access date and time of httpsession object.

To get access to servletcontext object

ServletContext sc=ses.getServletContext();

To know whether session is new or not

boolean b=ses.isNew();

• This method returns true when session object is just created object and its session id still yet to    be delivered(sent) to client(browser window), otherwise this method returns false (when session object and its session id is already there with client).

• If this method is called in firstservlet program of diagram (which receives only first request of the browser window) then this method returns true. If this method is called in other servlet programs of web application then this method returns false.

To invalidate the session

• Invalidating the session is the closing of the session between browser windowand web application. In this process the entire data from session object will beremoved and session object will be made as inactive object and ready for garbagecollection.

(a) When ses.invalidate()method is calied.

(b) When browser window is closed.

Note:Since session id will be stored as in memory cookie, value of the browser window and that in memory cookie will be destroyed once browser window isclosed so the session will be invalidated once browser window is closed.

(c) When MaxInactiveInterval/ sessionIdle timeout period is completed/ reached.

• If session object is continuously idle for certain amount of time then it will be invalidated automatically. The default session idle timeout period is 30 minutes (inmost of the servers). But this can be changed explicitly either by using programmatic approach or declarative approach.

(I) Programmatic approach(java code)

    In servlet prg/JSP prg

    ses.setMaxInactiveInterval(1500);

                                                  |

                                            Seconds    

(II) Declarative approach (xml code)

      In web.xml

     <web-app>

     <session-config>

     <session-timeout>20</session-timeout>

                                   |   

                             Minutes

   <session-config>

   <web-app>

• Once session idle timeout period or maxInactiveInterval period is completed the underlying webserver automatically expires the session (invalidates the session).

To know current maxInadiveInterval period/session Idletimeout period

int1=ses.getMaxlnactivelnterval() ;

Note:The above method returns 30 if no value is explicitly set as session idletimeout period.

If you set session idle timeout period in both programmatic and declarative approaches with two different values, can you tell me which value will be finally affected?

(A)Since, the code of servlet program executes after web.xml code so the time specified       through programmatic approach will be a effected by overriding the time specified through declarative approach.

• In httpsession objects the client data will be preserved in the form of session attribute values.

• Httpsession object and its session attributes are visible and accessible in all web resource programs of web application but they must get request from that particular browser window(client) for which this session attribute and session objects are created.

To create/modify session attribute

ses.setAttribute("age" ,new integer(30)) ;

ses .putValue (-, -) is deprecated method of setattribute (-,-)

To read session attribute value

Integer s1= (Integer) ses.getAttribute ("age") ;

ses.getValue (-, -) is deprecated method of getattribute (-,-)

To remove session attribute

ses.removeAttribute("age");

ses. removeValue (-, -) is deprecated method of removeattribute (-, -)

Develop the above Application

Step 1:Prepare the deployment directory structure of web application

Step 2:Develop the source code of above servlet program or web application.

personal.html

<HTML>

     <BODY bgcolor="lightblue" >

     <form action ="FirstServlet" method="Post" >

     <hl><center>

     <FONTCOLOR="#FF0033">PERSONALDETAILS</FONT></center></h1>

     <br><br>

     <table align="center">

     <center>

             <tr>

                 <td>Enter Name:</td>

                 <td><input type="text" name="name" ></td>

            </tr>

             <tr>

                 <td>Enter Address:</td>

                 <td><input type="text" name="address" ></td>

             </tr>

             <tr>

                 <td>Enter Age:</td>

                 <td><input type="text" name="age" ></td>

             </tr>

              <tr>

                  <td><input type="Submit" value="continue"></td>

             </tr>

    </BODY>

</HTML>

FirstServlet.java

 import java.io.*;

 import javax.servlet.*;

 import javax.servlet.http.*;

 import java.util.*;

 public class FirstServlet extends HttpServlet

   {

      public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

        {

          res. setContentType ( "text/html" );

          PrintWriter pw= res.getWriter( );

          String name=req.getParameter ("name") ;

          String address=req.getParameter("address");

          String age=req.getParameter ("age") ;

          HttpSession session=req.getSession();

          session.setAttribute ("name",name);

          session.setAttribute ("Address", address);

          session.setAttribute("age", age);

          pw.println("<BODY BGCOLOR=cyan:>");

          pw.println("<CENTER><Hl><FONT COLOR=red>Provide Your Exp & Skills</FONT></Hl></CENTER>");

          pw.println ("<FORM ACTION= 'SecondServlet' METHOD=GET>");

          pw.println("<TABLE ALIGN=CENTER>");

          pw.println("<TR>");

          pw.println("<TD>");

          pw.println("<H2><FONTCOLOR=BLUE>Enter Number of Years Exp:");

          pw.println("<INPUT TYPE=TEXT NAME=exp SIZE=6>");

          pw.println("</TD></TR>");

          pw.println("<TR>");

          pw.println("<TD>");

          pw.println("<H2><FONT COLOR=blue><B>Select Skills:</B>");

          pw.print("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;                           &nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

          pw.print("<SELECT NAME=skills>");

          pw.print (" <OP1'ION VALUE=JAVA>JAVA/J2EE </OPTION>");

          pw.print("<OPTION VALUE=.NET>.Net </OPTION>");

          pw.print("<OPTION VALUE=ORACLE>ORACLE lOG </OPTION>");

          pw.print("<OPTION VALUE=XML>XML & Web Services </OPTION>");

          pw.print("</SELECT>") ;

          pw.println("</TD></TR>") ;

          pw.println("<TR><TD>") ;

          pw.println("<INPUT TYPE=Submit value=Continue>");

          pw.println("</TABLE></BODY>");

        

        }// service()

  

   }//class

SecondServlet.java

import java.io.* ;

 import javax.servlet.*;

 import javax.servlet.http.*;

 import java.net.* ;

 import java.util.* ;

 public class SecondServlet extends HttpServlet

   {

      public void service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

         {

           res.setContentType("text/html" );

           PrintWriter pw=res.getWriter();

           String exp=req.getParameter("exp");

           String skills=req.getparameter("skills");

           HttpSession session=req.getSession();

           session.setAttribute("exp", exp );

           session.setAttribute("skills", skills);

           pw.println("<BOOY BGCOLOR=cyan>");

           pw.println("<CENTER><H1><FONT COLOR=red>Provide City & Salary</FONT>   </Hl></CENTER>");

           pw.println("<FORM ACTION='ThirdServlet' METHOD=GET>");

           pw.println("<TABLE ALIGN~CENTER>");

           pw.println("<TR>");

           pw.println("<TD>");

           pw.println("<H2><FONT COLOR=BLUE>Enter Preference City:");

           pw.println("<INPUT TYPE=TEXT NAME=city SIZE=6>");

           pw.println("</TD></TR>");

           pw.println("<TR>");

           pw.println("<TD>");

           pw.println("<H2><FONT COLOR=BLUE>Enter Expected Salary:");

           pw.println("<INPUT TYPE=TEXT NAME=sal SIZE=16>");

           pw.println("<!TD></TR>");

           pw.println("<TR><TD>");

           pw.println("<INPUT TYPE=SUBMIT VALUE=Submit>");

           pw.println("</TABLE></BODY>");

         }//service

   }//class

ThirdServlet.java

  import java.io.*;

 import javax.servlet.*;

 import javax.servlet.http.*;

 import java.net.* ;

 import java.util.*;

 import java.sql.*;

 public class ThirdServlet extends HttpServlet

    {

       public void service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

          {

            res. setContentType ( "text/html");

            PrintWriter pw = res.getWriter ( );

            String city=req.getParameter("city");

            String sal=req.getParameter("sal");

            HttpSession session =req.getSession ();

            String name =(String) session.getAttribut("name") ;

            String addr =(String) session.getAttribute ("Addr") ;

            String age =(String) session.getAttribute (" age") ;

            String exp =(String) session.getAttribute ("exp") ;

            String skills =(String) session.getAttribute ("skills") ;

            try

                {

                  Class.forName ("oracle.jdbc.driver.OracleDriver") ;

                  Connection con;

                  con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system" , "manager") ;

                  System.out.println("connected to oracle") ;

                  PreparedStatement pst=con.prepareStatement("INSERT INTO INFO VALUES(?,?,?,?,?,?,?)");

                  pst.setString(1,name);

                  pst.setString(2,addr);

                  pst.setString(3,age);

                  pst.setString(4,exp);

                  pst.setString(5,skills);

                  pst.setString(6,city);

                  pst.setString(7,sal);

                  int i = pst.executeUpdate();

                  if(i > 0)

                         {

                           pw.println("<BODY BGCOLOR=cyan>");

                           pw.println("<CENTER><H1><FONTCOLOR=red>Successfully Inserted</FONT></H1></CENTER>");

                           pw.println("<a href= personal.html>Home</a>");

                           pw.println("</table></body>");

                         }

                          else

                              {

                               pw.println("<BODY BGCOLOR=cyan>");

                               pw.println("<CENTER><H1><FONT COLOR=red>Try Again</FONT></H1></CENTER>");

                               pw.println("<a href= personal.html>Home</a>");

                              }

                } //try

                 catch (Exception e)

                      {

                 e.printStackTrace();

                 pw.println("<BODY BGCOLOR=cyan>");

                 pw.println("<CENTER><H1><FONT COLOR=red>Try Again</FONT></H1></CENTER>");

                 pw.println("<a href= personal.html>Home</a>");

                      }//service( )

    }//class

}

web.xml

<web-app>

      <servlet>

              <servlet-name>f</servlet-name>

              <servlet-class>FirstServlet</servlet-class>

      </servlet>

      <servlet-mapping>

                       <servlet-name>f</servlet-name>

                       <url-pattern>/FirstServlet</url-pattern>

      </servlet-mapping>

      <servlet>

              <servlet-name>s</servlet-name>

              <servlet-class>SecondServlet</servlet-class>

      </servlet>

      <servlet-mapping>

                      <servlet-narne>s</servlet-name>

                      <url-pattern>/SecondServlet</url-pattern>

      </servlet-mapping>

      <servlet>

               <servlet-name>t</servlet-name>

               <servlet-class>ThirdServlet</servlet-class>

      </servlet>

      <servlet-mapping>

                       <servlet-name>t</servlet-name>

                       <url-pattern> /ThirdServlet< /url-pattern>

      </servlet-mapping>

</web-app>

Step 3:Compile the source files of all servlet programs.

Step 4:Configure all the four servlet programs in web.xml file having four different url patterns.

Step 5:Start the server (Tomcat).

Step 6:Deploy the web application and copy SessionApp folder to Tomcat_home\ webapps folder.

Step 7:Create info table into Oracle database server.

Syntax:

Create table info(name varchar2(25),addr varchar2(100),age varchar2(1O),exp varchar 2(10),

Skill varchar2(25),city varchar2(25),sal varchar2(10));

Step 8:Test the web application.

Open browser window type thisURL:http://localhost:2020/SessionApp / personal. html

• If multiple clients (browser windows) send request to a web application in which httpsession object based session tracking is enabled, for every browser window one httpsession object will be created on the server having unique session id.

• In httpsession with cookies session tracking enabled web application the moment httpsession  object is created on server for browser window the servlet container automatically creates one in memory cookie having session id and adds that cookie to the response to be send to the browser window (no need of performing manual work),

• While working with httpsession objects, based on web application if browser window is closed in the middle of the session then the existing session will be invalidated and that session will not be continued in new browser window,

While working with httpsession object based application what happens if underlying serverisrestarted in the middle of the session?

(a)The session will be continued.

Server collects the data of httpsession objects and writes to files through serialization process having session id's when programmer shuts down the server, When server is restarted httpsession object will be created having old data and old session id's by reading data from the above said file through deserialization process, Due to this, the session will be continued even though the server is restarted in the middle of session,

Advantages of httpsession with cookies session tracking technique:

(1)Httpsession objects allocate memory on the server holding client during session as session attribute values, So, there will be data secrecy for client session data.

(2)Client data during session will not travel along with request and response over the network so this reduces network traffic between client and web server,

(3)The session attributes of Httpsession objects can take Java objects as values.

(4)All java based web server and application servers support this technique.

(5)This technique allows the programmer to specify session idle timeout period to invalidate in active session objects.

Disadvantages of httpsession with cookies session tracking technique:

(1) Httpsession object allocates memory on the server. This increases burden on the server.

(2) If cookies are restricted from coming to browser window this technique fails to perform session tracking.





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.