Sessions in Servlets

Handling Sessions in Java Servlets

 

ServletsHome

 

e-trainings-servlet-session-example
What is session? 

A collection of HTTP requests shared between a client and web server over a period of time. Session lifetime by default 30 min. and can be changed while creating session.

Once the session expires, the session destroyed and all its resources returned to the servlet engine.


Syntax:
 
 HttpSession session= request.getSession();

Methods:

getId()
getCreationTime()
getLastAccessedTime()

getAttribute(dataname)
setAttribute(dataName, dataValue);

URL:
 
SessionExample?dataName="Name"&dataValue="John"


Source Code for Session Example

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

public class SessionExample extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        HttpSession session = request.getSession(true);

        // print session info

        Date created = new Date(session.getCreationTime());
        Date accessed = new Date(session.getLastAccessedTime());
        out.println("ID " + session.getId());
        out.println("Created: " + created);
        out.println("Last Accessed: " + accessed);

        // set session info if needed

        String dataName = request.getParameter("dataName");
        if (dataName != null && dataName.length() > 0) {
            String dataValue = request.getParameter("dataValue");
            session.setAttribute(dataName, dataValue);
        }

        // print session contents

        Enumeration e = session.getAttributeNames();
        while(e.hasMoreElements()) {
            String name = (String)e.nextElement();
            String value = session.getAttribute(name).toString();
            out.println(name + " = " + value);
        }
    }
}
 
 
 
 

HTTP is a stateless protocol, means that it can't persist the information. 

 

It always treats each request as a new request. In HTTP client makes a connection to the server, sends the request, and gets the response, and finally the connection closed.



Session Tracking mechanism in servlets can be performed in the following ways.  

    1. Session 

    2. Cookie  

    3. Hidden form fields.

     4. URL rewriting.

 

 

Using Session in Java


 

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

public class SessionExample2 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession(true);

        // print session info

        Date created = new Date(session.getCreationTime());
        Date accessed = new Date(session.getLastAccessedTime());
        
        
        out.println("ID " + session.getId()+"<br>");
        out.println("Created: " + created+"<br>");
        out.println("Last Accessed: " + accessed+"<br>");

        // set session info if needed


        String uname = request.getParameter("uname");
        if (uname != null && uname.length() > 0) {
           // String uname = request.getParameter("uname");
            session.setAttribute("username" , uname);
        }
        
    

        // print session contents

        Enumeration e = session.getAttributeNames();
        
        while (e.hasMoreElements()) {
            String name = (String)e.nextElement();
            String value = session.getAttribute(name).toString();
            out.println(name + " = " + value+"<br>");
        }
        
    //  session = request.getSession(false);
        if (session != null) {
           // session.invalidate();
        	session.removeAttribute("username");
        	//session.removeValue("uname");
        }
        out.println(" <br> Session  username removed <br>");
        
        session.setAttribute("City", "Hyderabad");
        session.setAttribute("Email", "info@example.com");
        
        out.println("Session User " + session.getAttribute("username")+"<br>");
        
        
        
    }
}

 Output:

 

 

e-trainings-Servlet-sessions-demo


 


 

Session Tracking Example in Java

 

import java.io.*;
import java.util.Enumeration;

//import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;

//java session visitor count example

public class SessionTrackingDemo extends HttpServlet {
	int count; 

	   public void  init(FilterConfig config) throws ServletException {
	      // Reset hit counter.
	     count = 0;
	   }

  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

  //  Enumeration  enum;
    HttpSession session = req.getSession(true);

    // count = (Integer)session.getAttribute("count");

  
  
  if (count == 0)
      count = 1;

    else
    {
      count =  count  + 1;
      session.setAttribute("count", count);

    out.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>");
    out.println("<BODY><H1>Session Tracking Demo</H1>");


    out.println("You've visited this page " + count +   ((count == 1) ? " time." : " times."));

    out.println("<P>");

    out.println("<H2>Here is your session data:</H2>");
     
     
      out.println("SESSIONID - " + session.getId()+"<br>");
      
      Enumeration e = session.getAttributeNames();
     
      while (e.hasMoreElements()) { 

       String name = (String) e.nextElement();
      out.println(name + ": " + session.getAttribute(name) + "<BR>"); 


     }
    out.println("</BODY></HTML>");
  }
} 
  
}

 

 Output:


 

 

 

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Shoppingcart using PHP Sessions - Miniproject

Export Data to Excel with PHP and MySQL