All IT Courses 50% Off
JAVA Tutorials

What is Session Management?

Session management is used to store session information of a user. It is also known as Session tracking. Session Management is used to maintain the state of a user because the HTTP protocol is stateless. Every request made to the server by the user, it is considered as a new request. Hence, it becomes essential to store the session information to recognize the user.

Session Tracking Techniques:

Session Tracking is done using the below four techniques:

  1. Cookies
  2. Hidden Form Field
  3. URL Rewriting
  4. HttpSession

1] Cookies:

Cookies are a small piece of information that is sent by the server along with the response and is stored on the client’s system. There are two types of cookies: 

  • Non-persistent cookie: These cookies are valid for only a single session, and cookies will be removed when the user closes the browser.
  • Persistent cookie: These cookies are valid for multiple sessions and cookies will not be removed when the user close the browser. Cookies will only remove when the user log out/sign out.

Methods used in Cookie Class:

  • public void setMaxAge(int expiry): This will set the maximum age of the cookie in seconds.
  • public String getName(): This method will return the name of the cookie and the name cannot be changed after it has been created.
  • public String getValue(): It returns the value of the cookie.
  • public void setName(String name): This is used to change the name of the cookie.
  • public void setValue(String value): This is used to change the value of the cookie.
  • public void addCookie(Cookie ck): This method of HttpServletResponse interface is used to add cookie in response object.
  • public Cookie[] getCookies(): This method of HttpServletRequest interface is used to return all the cookies from the browser.

Example: Index.html

<form method="post" action="validate">
    Name:<input type="text" name="user" /><br/>
    Password:<input type="text" name="pass" ><br/>
    <input type="submit" value="submit">
</form>

MyServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("user");
        String pass = request.getParameter("pass"); 
        if(pass.equals("1234"))
        {
            Cookie ck = new Cookie("username", name);
            response.addCookie(ck);
            response.sendRedirect("First");
        }
    }
}

First.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 public class First extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Cookie[] cks = request.getCookies();
        out.println("Welcome "+ cks[0].getValue());
    }
}

2] Hidden Form Field:

In Hidden form Field, a hidden text field is used to maintain the session information.

Syntax: <input type=”hidden” name=”uname” value=”ABC”>  

Hidden form Field always work whether cookies are enable or not and are maintained at sever side.

Example:

First.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class First extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
//getting value submitted in form from HTML file
        String user = request.getParameter("user"); 
        //creating a new hidden form field
        out.println("<form action='Second'>");
        out.println("<input type='hidden' name='user' value='"+user+"'>");
        out.println("<input type='submit' value='submit' >");
        out.println("</form>");
    }
}

Second.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Second extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        //getting parameter from the hidden field
        String user = request.getParameter("user");
        out.println("Welcome "+user);
    }
}

3] URL Rewriting

In URL Rewriting a token or an identifier is added to the URL of the next Servlet Request. This token or identifier contains value in the form of name/value pairs separated by equal ( = ) sign.

Syntax: url?name1=value1&name2=value2&??

It will also work whether a cookie is enable or not. The main disadvantage of URL Rewriting approach is that it only works with the links.

Example

MyServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("user");
        String pass = request.getParameter("pass");
        if(pass.equals("1234"))
        {
            response.sendRedirect("First?user_name="+ name);
        }
    }   
}

First.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class First extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String user = request.getParameter("user_name");
        out.println("Welcome "+user);
    }
}

4] HttpSession

In HttpSession web container creates a session id for each user which is then used to identify the user. HttpSession are used to perform two tasks:

  1. bind the objects.
  2. View and change the information about a session such as session id, creation time, etc.

Methods used in HttpSession:

  • public HttpSession getSession(): It will return the current session associated with the request, and if the request does not have any session then it will create one.
  • public HttpSession getSession(boolean create): It will return the current HttpSession associated with this request, and if there is no current session established and value of create is true it will then returns a new session.
  • public String getId(): It will return a string containing the unique identifier value.
  • public long getCreationTime(): It returns the time when this session was created.
  • public long getLastAccessedTime(): It returns the last time the client sent a request associated.
  • public void invalidate(): It will invalidate the session and then unbinds any objects which are bound to it.

Example:

Validate.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Validate extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("user");
        String pass = request.getParameter("pass");
        if(pass.equals("1234"))
        {
            //creating a session
            HttpSession session = request.getSession();
            session.setAttribute("user", name);
            response.sendRedirect("Welcome");
        }
    }
}

Welcome.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String user = (String)session.getAttribute("user");
        out.println("Hello "+user);
    }
}
Facebook Comments
Tags

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Back to top button
Close
Close

Get Python Course
worth 499$ for FREE!

Offer valid for 1st 20 seats only, Hurry up!!

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

H2kinfosys Blog will use the information you provide on this form to be in touch with you and to provide updates and marketing.