Understanding HttpSession in JSP and Servlet - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Understanding HttpSession in JSP and Servlet

Share This

We know that HTTP is a stateless protocol. It provides no built-in way for a server to recognize that a sequence of requests all originated from the same user. 


Privacy advocates may consider this a feature, but most web programmers see it as a major headache because web applications aren't stateless


Robust web applications need to interact back and forth with the user, remembering information about the user between requests. 


For example, in a shopping cart application, a client has to be able to put items into his virtual cart, and the server has to remember his items until he checks out several page requests later, or sometimes even days later!


The solution, as you may have already guessed, is for a client to introduce itself as it makes each request. Each client needs to provide a unique identifier that lets the server identify it, or it needs to give some information that the server can use to properly handle the request.



How to Manage Session


HTTP and session state have to do with how a Web Application uses HTTP to maintain the state of a user's session. HTTP is a connection-oriented protocol; it goes over TCP and not UDP.


When a browser sends a request to a server, the browser establishes a connection, sends an HTTP request, and consumes an HTTP response. If the response is an HTML page, then the client will typically parse the page looking for other tags that require data to be downloaded.


If there are such tags on the page, then the browser will re-use the same connection to download that data. However, as soon as the page "transaction" is complete, the browser will close the connection.


This has a major impact on the way Web Applications work. Most applications maintain data on behalf of a user and need to track users. The data may be a shopping cart or simply user preferences, but as each user request is sent over a different connection, there is no way to link subsequent requests and keep the state.



Client Identification

Given the preceding, you should be curious as to how a server identifies a client. Essentially, the client and server code need to exchange some identifier that uniquely identifies this client to this server. Note that this identifier does not uniquely identify this client on the Internet; it is a value that only means something to the server that creates it. This identifier can be exchanged either with or without the client's cooperation.


Session Scope

The HttpSession object is a data container. The data stored in the container are private to a given client and will persist until the server destroys the client's session. HttpSession has four methods that allow objects to be used with session scope.



Example
Source Code of index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <form action="LoginServ"> <input type="text" name="name"> <input type="password" name="pass"> <input type="submit"> </form> </body> </html>
Source Code of LoginServ.java

package com.t4b.test; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class LoginServ */ @WebServlet("/LoginServ") public class LoginServ extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LoginServ() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); System.out.print(request.getParameter("name")); System.out.print(request.getParameter("pass")); if (request.getParameter("name").equalsIgnoreCase("user1") && request.getParameter("pass").equalsIgnoreCase("1234")) { session.setAttribute("name", request.getParameter("name")); RequestDispatcher rd = request.getRequestDispatcher("home.jsp"); rd.forward(request, response); } else { RequestDispatcher rd = request.getRequestDispatcher("index.jsp"); rd.forward(request, response); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Source Code of home.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <h1>Home page</h1> <p>Welcome <%=session.getAttribute("name") %></p> </body> </html>

Let's try another code

Source Code of index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <%@ page import="java.io.*,java.util.*"%> <% // Get session creation time. Date createTime = new Date(session.getCreationTime()); // Get last access time of this web page. Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = "Welcome Back to my website"; Integer visitCount = new Integer(0); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD"); // Check if this is new comer on your web page. if (session.isNew()) { title = "Welcome to my website"; session.setAttribute(userIDKey, userID); session.setAttribute(visitCountKey, visitCount); } visitCount = Integer.parseInt("" + session.getAttribute(visitCountKey)); visitCount = visitCount + 1; userID = (String) session.getAttribute(userIDKey); session.setAttribute(visitCountKey, visitCount); %> <center> <h1>Session Tracking</h1> </center> <table border="1" align="center"> <tr bgcolor="#949494"> <th>Session info</th> <th>Value</th> </tr> <tr> <td>id</td> <td> <% out.print(session.getId()); %> </td> </tr> <tr> <td>Creation Time</td> <td> <% out.print(createTime); %> </td> </tr> <tr> <td>Time of Last Access</td> <td> <% out.print(lastAccessTime); %> </td> </tr> <tr> <td>User ID</td> <td> <% out.print(userID); %> </td> </tr> <tr> <td>Number of visits</td> <td> <% out.print(visitCount); %> </td> </tr> </table> </body> </html>



Happy Exploring!

No comments:

Post a Comment