Servlets - SPLessons

Servlet HttpSession

Chapter 23

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Servlet HttpSession

Servlet HttpSession

shape Introduction

Servlet HttpSession, HttpSession object remembers the client data across multiple requests. For HttpSession, memory is allocated in the server in the form of Session Attribute. The HttpSession is an object of servlet container by implementing java class to javax.servlet.http.HttpSession interface. HttpSession contains Session-Id and this Session-Id goes to browser window from the web application and comes back to the web application from browser window in the form of cookies.

shape Conceptual
figure

Create HttpSession Object

shape Methods

HttpSession session = request.getSession();

For one browser window, the above method creates the HttpSession object on the server. If HttpSession is already created, then that created HttpSession object can be used, otherwise new HttpSession object is created.

HttpSession session = request.getSession(false);

This method checks the HttpSession is existing or not. If HttpSession is not available then it returns null, but this method does not create new HttpSession.

HttpSession session = request.getSession(true);

This method also checks whether the HttpSession is existing or not. If HttpSession is not available then it creates new HttpSession.

String id = session.getId();

This method is used to know session id.
long ms = session.getCreateTime();

To Know Object Creation time/Session Starting time

Date date = new Date(ms);

This code is used to print the date and time of HttpSession object created. (January 1, 1970 GMT).
ServletContext sessionContext = session.getServletContext();

To Access ServletContext Object

session.setMaxInactiveInterval(sec);//sec indicates second time

To set the Session time
session.getMaxInactiveInterval(sec);
To get the Session time interval

shape Example

index.html

<html>
<form action="./welcome">
		 Enter name:<input type="text" name="username">
		 Enter Email:<input type="text" name="emailId">
		<input type="submit" value="submit">
	 </form>
</html>

Here the developer just created two text boxes one is to enter the name and second one is enter email.
web.xml

<web-app>
  <servlet>
    <servlet-name>
     DemoSessionId
    </servlet-name>
    <servlet-class>
     DemoSessionId
    </servlet-class>
  </servlet>
   
  <servlet>
    <servlet-name>
     SessionId
    </servlet-name>
    <servlet-class>
     SessionId
    </servlet-class>
  </servlet>
 
  <servlet-mapping>
      <servlet-name>
       DemoSessionId
      </servlet-name>
  <url-pattern>
      /welcome
  </url-pattern>
  </servlet-mapping>
   
  <servlet-mapping>
      <servlet-name>
       SessionId
       </servlet-name>
    <url-pattern>
   /servlet2
   </url-pattern>
</servlet-mapping>
   
</web-app>

Make sure that should be same and also URL name should be match with HTML form.
DemoSessionId.java

import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
 
public class DemoSessionId extends HttpServlet {
 
     
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
         
        //get the value from the text from HTML
        String uname = request.getParameter("username");
        String email = request.getParameter("emailId");
         
        //Create HttpSession object
        HttpSession session = request.getSession();
         
        //set the username in the session
        session.setAttribute("uname", uname);
        session.setAttribute("emailId", email);
         
        out.print("<h2>Enter your country:<input type='text' name='country'></h2>"); 
        out.println("<a href='servlet2'>

<h2>go</h2>

 
</a>");
        out.flush();
        out.close();
    }
 
}

get the value from the text from HTML.

String uname = request.getParameter("username");
        String email = request.getParameter("emailId");

Create HttpSession object.

 HttpSession session = request.getSession();

Set the username in the session.

session.setAttribute("uname", uname);
        session.setAttribute("emailId", email);

SessioId.java

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

public class SessionId extends HttpServlet {
 
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
         
        //get the values from the request
        String country = request.getParameter("country");
         
        HttpSession session = request.getSession(false);
         
        //This from get sessionID
        String sessionId = session.getId();
         
        //Get the username from the session
        String userName = (String)session.getAttribute("uname");
         
        //Get the emailId from the session
        String email = (String)session.getAttribute("emailId");
        out.println("<h2>This is your name get from the session::"+userName+"</h2>");
        out.println("<h2>This is your emailId get from the session::"+email+"</h2>");
        out.println("<h2>This is your country Show it null because it is not in session ::"+country+"</h2>");
        out.println("<h2>This is the sessionId value :::"+sessionId+"</h2>");
        out.flush();
        out.close();
    }
 
}

Get the values from the request.

String country = request.getParameter("country");
          
        HttpSession session = request.getSession(false);

This from get sessionID.

String sessionId = session.getId();

Get the username from the session

String userName = (String)session.getAttribute("uname");

Get the emailId from the session.

String email = (String)session.getAttribute("emailId"); 

Output
Following is the page generated from the HTML where details can be enterd.

Following is the servlet2 page where enter the country name.

Here the total information will be displayed.


Difference Between Servlet Session And Servlet Context

shape Description

A Servlet Session is an altogether different thing from a Servlet Context.

A HttpSession is a component used to reproduce and keep up a persistent client Session between a Web Browser and Web Application, to a great extent oversaw by the Servlet Container. The HTTP convention is stateless, it is basically a request-response plot, so Servlet Sessions are kept up by passing a novel HTTP treat an incentive for each demand, or by powerfully incorporating an identifier in Servlet URLs, called as URL-rewriting.

A ServletContext speaks to the general design of the Servlet Container and has a few techniques to get arrangement parameters, trade information among Servlets, forward requests and load assets. The Servlet Context is typically gotten by implication through the ServletConfig question, go to a Servlet’s init(ServletConfig) technique, or from the Servlet getServletConfig() strategy.

Summary

shape Key Points

  • Servlet HttpSession – HttpSession object allocate memory on the server, so it get burden to the server.
  • Container creates session id to the request.
  • An object of HttpSession will be provided by HttpServletRequest interface.