Session in Servlets Tutorial

As HTTP protocol is stateless each request treated as new and after request is processed connection is terminates.For maintaining the state of user or tracking session we have following ways.

  • Cookie
  • URL Rewriting
  • Hidden input field
  • Session

HttpSession interface provides methods to create session,store information and get information.

How to create of HttpSession Object

The HttpServletRequest interface provides two methods to get the object of HttpSession.

  • public HttpSession getSession(): It returns the current session associated with this request, or if the request does not have a session, creates one.
  • public HttpSession getSession(boolean create):It returns the current HttpSession associated with this request or, if there is no current session and if create is true, returns a new session.If create is false then existing associated session object is returned.

Commonly used methods of HttpSession interface

  • public String getId():It returns a string containing the unique identifier value.
  • public void setAttribute(String name,Object value): It binds an object to this session, using the name specified.
  • public void removeAttribute(String name): It removes the object bound with the specified name from this session.
  • public void invalidate():It Invalidates this session then unbinds any objects bound to it.It is used to logout user.
  • public long getCreationTime():It returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
  • public long getLastAccessedTime():It returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.

Example to use HttpSession

Here I am taking example login user and show profile page.

users.sql

CREATE TABLE users
(
ID int NOT NULL AUTO_INCREMENT,
name varchar(100),
email varchar(100),
password varchar(100),
PRIMARY KEY (ID)
);

LoginServlet.java


package com.startwithjava;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
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 LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email    = request.getParameter("email");
String password = request.getParameter("password");
String name ="";
int userId=0;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/expertwebindia","root","");
Statement st = con.createStatement();
ResultSet rst = st.executeQuery("SELECT * FROM users WHERE email='"+email+"' AND password='"+password+"'");
if(rst!=null){
HttpSession sesion = request.getSession(true);
while(rst.next()){
name = rst.getString("name");
userId = rst.getInt("id");
System.out.println("Id"+userId);
}
sesion.setAttribute("userId", userId);
response.sendRedirect("profile");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

ProfileServlet.java


package com.startwithjava;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
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;
public class ProfileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProfileServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name="";
String email="";
HttpSession session =null;
session = request.getSession(false);
if(session!=null){
try {
int id = Integer.parseInt(session.getAttribute("userId").toString());
System.out.println("Id"+id);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/expertwebindia","root","");
Statement st = con.createStatement();
ResultSet rst = st.executeQuery("SELECT * FROM users WHERE id="+id);

while(rst.next()){
name  = rst.getString("name");
email = rst.getString("email");
System.out.println("email"+email);
}
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("name", name);
request.setAttribute("email", email);
RequestDispatcher rd = request.getRequestDispatcher("/profile.jsp");
rd.include(request, response);
}else{
response.sendRedirect("login.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}

LogOutServlet.java


package com.startwithjava;
import java.io.IOException;
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 LogOutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LogOutServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession sesion = request.getSession(false);
sesion.invalidate();
response.sendRedirect("login.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}

login.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>
<form action="login" method="post">
<table>
<tr>
<td>Email</td>
</tr>
<tr>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Password</td>
</tr>
<tr>
<td><input type="text" name="password"></td>
</tr>
<tr>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>

profile.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Dashboard</title>
</head>
<body>

<h1>User Dashboard</h1>

Name : <c:out value="${name}"/>

Email : <c:out value="${email}"/>
<a href="logout">Logout</a>
</body>
</html>

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.startwithjava.LoginServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>profile</servlet-name>
<servlet-class>com.startwithjava.ProfileServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>profile</servlet-name>
<url-pattern>/profile</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>logout</servlet-name>
<servlet-class>com.startwithjava.LogOutServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>logout</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>
</web-app>

Leave a Reply