Servlet Tutorial

Http Session

HttpSession is a technique of session management which maintains an identity of a client for a period of time across the network for making 'n' number of requests for obtaining 'n' number of responses. During the period of session, all the requests and responses are consecutive.

Steps for developing HttpSession applications:

  1. Obtain an object of javax.servlet.http.HttpSession interface.

    In order to obtain an object of HttpSession we have to use the following two methods which are present in HttpServletRequest

    http session

    For example:

    HttpSession hs=req.getSession ();
    HttpSession hs=req.getSession (true);
                                    

    When we use method-ii the boolean value can be either true or false:

    Case-1: Session not created and boolean value is true. Session will be created newly.

    For example:

    HttpSession hs=req.getSession (true);
                                    

    Case-2: Session not created and boolean value is false. Session will not be created at all.

    For example:

    HttpSession hs=req.getSession (false);
                                    

    Case-3: Session already created and boolean value is true. Existing or old session will be continued with checking.

    HttpSession hs=req.getSession (true);
                                    

    Case-4: Session already created and boolean value is false. Existing or old session will be continued without any checking.

    For example:

    HttpSession hs=req.getSession (false);
                                    
  2. Put the values into HttpSession object by using the following methods which are present in HttpSession:

    http session put value http session set attribute

    Here, String represents session variable name known as key and Object represents session value. In HttpSession object the data is organizing in the form of (key, value) pair.

    For example:

    hs.putValue ("name","kalyan"); hs.setAttribute ("address",s2);
  3. Get the values from HttpSession object by using the following methods which are present in HttpSession:

    http session get value attribute

    For example:

    Object obj1=hs.getAttribute ("name"); 
    Object obj2=hs.getValue ("address");
                                    

Other methods in HttpSession:

  1. public void setMaxInactiveInterval (long sec):

    In most of the popular web sites an identity of the client will be maintained for a period of 30 minutes. When the time interval between first request and second request i.e., if the time delay between one request to another request is 30 minutes then automatically the server will eliminate the identity of the client.

    In order to set our own session out time or maximum session active time, we use this method. In this method, we specify the session active time in terms of seconds.

    For example:

    hs.setMaxInactiveInterval (60*60);
                                    
  2. public boolean isNew ():

    This method returns true when the session is created newly otherwise it returns false for old sessions.

    For example:

    boolean b=hs.isNew ();
                                    
  3. public void removeAttribute (String):

    This method is used for removing one of the session attribute name along with its value.

    For example:

    hs.removeAttribute ("address");
                                    
  4. publicEnumerationgetAttributeNames ():

    This method is used for obtaining all the session variable names.

    For example:

    get attribute names
    Enumeration en=hs.getAttributeNames ();
    While (en.hasMoreElements ())
    {
        Object kname=en.nextElement (); 
        String key= (String) kname;
        Object val=req.getAttribute (key);
    }
                                    
  5. public void invalidate ():

    This method is used for invalidate the identity of the client permanently i.e., all the values of session object will be removed completely.

    For example:

    hs.invalidate ();
                                    
  6. publiclonggetLastAccessTime():

    This method is used for obtaining last access time.

    For example:

    long t=hs.getLastAccessTime ();
                                    
  7. public long getId ():

    This method is used for obtaining session id of a client which is created by servlet container.

    For example:

    long sid=hs.getId ();
                                    

Develop the servlets which illustrate the concept of HttpSession?

Answer:

web.xml:

<web-app>
    <servlet>
        <servlet-name>s1</servlet-name>
        <servlet-class>FirstServ</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>s2</servlet-name>
        <servlet-class>SecondServ</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>s3</servlet-name>
        <servlet-class>FinalServ</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>s1</servlet-name>
        <url-pattern>/test1</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>s2</servlet-name>
        <url-pattern>/test2</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>s3</servlet-name>
        <url-pattern>/test3</url-pattern>
    </servlet-mapping>
</web-app>
                        

personal.html:

<html>
    <title>Complete example</title>
    <body>
    <center>
        <form name="ex" action="./test1" method="post">
            <table border="1">
                <tr>
                    <th align="left">Enter ur name : </th>
                    <td><input type="text" name="ex_name" value=""></td>
                </tr>
                <tr>
                    <th align="left">Enter ur address : </th>
                    <td><textarea name="ex_add" value=""></textarea></td>
                </tr>
                <tr>
                    <th align="left">Enter ur age : </th>
                    <td><input type="text" name="ex_age" value=""></td>
                </tr>
                <tr>
                <table>
                    <tr>
                        <td align="center"><input type="submit" name="ex_continue" value="Continue"></td>
                    </tr>
                </table>
                </tr>
            </table>
        </form>
    </center>
    </body>
</html>
                        

Databasetable (info):

create table info (
name varchar2 (13),
addr varchar2 (33),
age number (2),
exp number (2),
skills varchar2 (13),
sal number (7,2),
loc varchar2 (17)
);
/
                        

FirstServ.java:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class FirstServ extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        String name1 = req.getParameter("ex_name");
        String address1 = req.getParameter("ex_add");
        String age1 = req.getParameter("ex_age");
        HttpSession hs = req.getSession(true);
        hs.putValue("namehs", name1); // we can also use setAttribute
        hs.putValue("addresshs", address1); // we can also use setAttribute
        hs.putValue("agehs", age1);
        pw.println("<html><title>First Servlet</title><body bgcolor=\"green\"><center>");
        pw.println("<form name=\"first\" action=\"./test2\" method=\"post\"><table bgcolor=\"lightblue\">");
        pw.println("<tr><th>Enter   ur   experience   :   </th><td><input   type=\"text\"   name=\"first_exp\"value=\"\">");
        pw.println("</td></tr><tr><th>Enter  ur  skills  :  </th><td><input  type=\"text\"  name=\"first_skills\" value=\"\">");
        pw.println("</td></tr><table><tr><td  align=\"center\"><input type=\"submit\" name=\"first_submit\"value=\"Continue\">");
        pw.println("</td></tr></table></table></form></center></body></html>");
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doGet(req, res);
    }
};
                        

SecondServ.java:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class SecondServ extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        String exp1 = req.getParameter("first_exp");
        String skills1 = req.getParameter("first_skills");
        HttpSession hs = req.getSession(false);
        hs.putValue("exphs", exp1); // we can also use setAttribute
        hs.putValue ("skillshs",skills1); // we can also use setAttribute 
        pw.println ("<html><title>Second Servlet</title><body bgcolor=\"green\"><center>");
        pw.println("<form	name=\"second\"	action=\"./test3\"	method=\"post\"><table bgcolor=\"lightblue\">");
        pw.println("<tr><th>Enter  expected  salary  :  </th><td><input  type=\"text\"  name=\"second_sal\"value=\"\">");
        pw.println("</td></tr><tr><th>Enter	preffered	location	:	</th><td><input	type=\"text\"name=\"second_loc\" value=\"\">");
        pw.println("</td></tr><table><tr><td	align=\"center\"><input	type=\"submit\" name=\"second_submit\" value=\"Submit\">");
        pw.println("</td></tr></table></table></form></center></body></html>");
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doGet(req, res);
    }
};
                        

FinalServ.java:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;

public class FinalServ extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        String sal1 = req.getParameter("second_sal");
        float salary = Float.parseFloat(sal1);
        String location = req.getParameter("second_loc");
        HttpSession hs = req.getSession(false);
        String name = (String) hs.getAttribute("namehs");
        String address = (String) hs.getAttribute("addresshs");
        String age1 = (String) hs.getAttribute("agehs");
        int age = Integer.parseInt(age1);
        String exp = (String) hs.getAttribute("exphs");
        int experiance = Integer.parseInt(exp);
        String skills = (String) hs.getAttribute("skillshs");
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:Hanuman", "scott", "tiger");
            PreparedStatement ps = con.prepareStatement("insert into info values (?,?,?,?,?,?,?)");
            ps.setString(1, name);
            ps.setString(2, address);
            ps.setInt(3, age);
            ps.setInt(4, experiance);
            ps.setString(5, skills);
            ps.setFloat(6, salary);
            ps.setString(7, location);
            int j = ps.executeUpdate();
            if (j > 0) {
                pw.println("<html><body bgcolor=\"lightblue\"><center><h1><font color=\"red\"> Successfully ");
                pw.println("Inserted</font></h1></center><a  href=\"personal.html\">Home</a></body></html>");
            } else {
                pw.println("<html><body bgcolor=\"cyan\"><center><h1><font color=\"red\">Try Again");
                pw.println("</font></h1></center><a  href=\"personal.html\">Home</a></body></html>");
            }
        } catch (Exception e) {
            pw.println("<html><body bgcolor=\"cyan\"><center><h1><font color=\"red\">Try Again");
            pw.println("</font></h1></center><a href=\"personal.html\">Home</a></body></html>");
        }
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doGet(req, res);
    }
};
                        

Advantages of HttpSession:

  1. There is no restriction on size of HttpSession object. Since, a single object can hold different type of values which are related to client identity.
  2. Network traffic flow is very less. Since, only session id is exchanging between client and server.
  3. An object of HttpSession neither exists at client side not exists at server.