Thursday, March 26, 2020

HttpSession Interface

HttpSession Interface


HttpSession Interface is used for session tracking like cookies, URL rewriting. HttpSession provides a mechanism to track the user activity across multiple pages, request or visit a Web site and to store information about that user.

HttpSession interface object is constructed by the servlet container to establish a session between an HTTP client and an HTTP server. The session can be maintained for a specified period of time, over multiple pages, even for more than one connection. A session corresponds to one user, who may interact with the website several times.

httpsession

How the HttpSession Interface works?


  • With the HttpSession interface, object servlet can view, update and retrieve information for the corresponding sessions, like session identifier, time of creation and last access time of the user.
  • HttpSession Interface enables the servlets to bind the objects to sessions, allowing user information to persist across multiple user connections

The servlet container creates a session id for individual users. This id is used to identify any particular user. The scope of the Session information is only inside the current web application (ServletContext). The information stored under a context will not be available in other (ServletContext).


HttpSessionBindingListenter

The servlet container first checks whether the object that is being stored or removed from the session by the web application implements HttpSessionBindingListenter or not. If yes, the servlet notifies the object this will be bound or unbound from the session. After the binding is complete the notifications will be sent to the objects. The notifications for expired and invalidated sessions are sent after the session is invalidated or expired.

HttpSession Interface


Method  Description
public HttpSession getSession() This method returns the current session corresponding to the request, or if the request does not have a session a new request is created
public HttpSession getSession(boolean create) This method returns the current HttpSession corresponding to the request, or if there is no current session and create is true, returns a new session
setAttribute(String name, value) This method binds an object to this session with the specified name
getAttribute(String name) This method returns the object bound with the specified name in this session, or null if no object is bound with the specified name
public String getId() This method returns a string with the unique identifier value
public long getCreationTime() This method returns the time of creation, This is measured in milliseconds since midnight January 1, 1970 GMT
public long getLastAccessedTime() This method returns the last time the client sent a request associated with this session, as measured milliseconds since midnight January 1, 1970 GMT
public void invalidate() This method invalidates this session then unbinds any objects bound to the session.
removeAttribute(String name) This method removes the object bound with the specified name with the corresponding session.

HttpSession Example


We can demonstrate HttpSession with the following example. This is a simple login-logout application and we are storing session information in the session object. The application has following files,


  1. index.html
  2. login.html
  3. LoginServlet.java
  4. ProfileServlet.java
  5. Logout.servlet.java

index.html


<html>
<head>
<title>Welcome</title>
</head>
<body bgcolor="yellow">
<h2>
<a href="login.html">login</a>
<a href="http://localhost:8087/TestSesssion/LogoutServlet">logout</a>
<a href="http://localhost:8087/TestSession/ProfileServlet">Profile</a>
</h2>
</body>
</html>

login.html


<html>
<head>
<title>Login</title>
</head>
<body bgcolor="yellow">
<form method="post" action="LoginServlet">
<input type="text" placeholder="Enter Name" name="name"><br>
<input type="password" placeholder="Enter Passwod" name="pass"></br>
<input type="submit" value="login"><br>
</form>
<br>
New User?
<a href="">Sign up</a>
</body>

</html>

LoginServlet.java


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;
    public LoginServlet() {
        super();
  
    }
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           response.setContentType("text/html");
           PrintWriter pout=response.getWriter();
           pout.append("<html><body>");
           String name=request.getParameter("name");
           String pass=request.getParameter("pass");
           if(name.equalsIgnoreCase("admin") && pass.equalsIgnoreCase("123"))
           {

                HttpSession session=request.getSession();
                session.setAttribute("name", name);
                pout.append("<h3>You are successfully logged in</h3>");
           }else
           {
                pout.append("<h3>Wrong Username or password</h3>");
           }
           pout.append("</body></html>");
     RequestDispatcher rd=request.getRequestDispatcher("index.html");
           rd.include(request, response);
     }

}



ProfileServlet.java


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ProfileServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;
      
    public ProfileServlet() {
        super();
    }
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           response.setContentType("text/html");
           PrintWriter pout=response.getWriter();
           pout.append("<html><body>");
           HttpSession session=request.getSession();
           String name=(String)session.getAttribute("name");
           if(name!=null)
           {
                pout.append("<h3>Welcome "+name+"</h3>"); 
           }else
           {
                pout.append("<h3>You are not logged in.</h3>");
           }
           pout.append("</body></html>");
           RequestDispatcher rd=request.getRequestDispatcher("index.html");
           rd.include(request, response);
     }

}


LogoutServlet.java


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LogoutServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;
      
    public LogoutServlet() {
        super();
    }
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           response.setContentType("text/html");
           PrintWriter pout=response.getWriter();
           pout.append("<html><body>");
           HttpSession session=request.getSession();
           session.invalidate();
           pout.append("<h3>You are logged out successfully</h3>");
           pout.append("</body></html>");
    RequestDispatcher rd=request.getRequestDispatcher("index.html");
           rd.include(request, response);
     }

}


Result: