Monday, 1 October 2012

Servlet HttpSession Example


Session tracking methods

Cookies are small files that the servlet can store on the client computer, and retrieve later
URL rewriting: You can append a unique ID after the URL to identify the user
Hidden <form> fields can be used to store a unique ID
Java’s Session Tracking API (HttpSession)
The session tracking API is in javax.servlet.http.HttpSession and we have to follow below steps to use the session tracking API:
HttpSession session = request.getSession(); 
Returns the session associated with this request If there was no associated session, one is created
HttpSession session = request.getSession(true);
Store information in the session and retrieve it as needed:
session.setAttribute(name, value); 
Object obj = getAttribute(name);

HTTP is stateless, so the programmer must do something to remember session information There are multiple ways to remember session information The session ends when the user quits the browser (or a session may be set to time out) Some information must be kept longer than just within a session


A JSP page which is checks the session always and it is there it says you are are already logged in and also invoking the servlet
<%@ page language="java" contentType="text/html; charset=UTF-8"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>Insert title here</title>
   String userName =(String) session.getAttribute("UserName");
   if(userName !=null){
      out.println("Hi "+ userName +" You are logged in");
User name: <inputtype="text"name="user"> Password: <input
type="text"name="pass"> <inputtype="submit"value="Submit">


A servlet to create session and send the response
package com.vinod.test;


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;

public class SessionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<HTML><TITLE>HttpSession Example</TITLE><BODY>");
HttpSession session = request.getSession(true);
String value = (String) session.getAttribute("UserName");
if (value == null) {
String user = request.getParameter("user");
session.setAttribute("UserName", user);
out.println("Session created with" + session.getId());
out.println("<H2>Hello " + request.getParameter("user") + " you logged </H2><HR>");
Run jsp and submit with username and password
Run the same jsp again (We can see the session created and welcome message printed)