JAVA CODE FOR SESSION MANAGEMENT USING SERVLET-SESSION IDS | URDINESH

Software Programming, Tutorials, Interview Preparations,Stock Market,BSE/NSE, General informations

Tuesday, May 20, 2014

JAVA CODE FOR SESSION MANAGEMENT USING SERVLET-SESSION IDS




PROGRAM:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionSnoop extends HttpServlet
{
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException
{
            res.setContentType("text/html");
            PrintWriter out = res.getWriter();
HttpSession session = req.getSession(true);
 Integer count = (Integer)session.getValue("snoop.count");
 if (count == null)
      count = new Integer(1);
 else
      count = new Integer(count.intValue() + 1);
 session.putValue("snoop.count", count);
 out.println("<HTML><HEAD><TITLE>SessionSnoop</TITLE></HEAD>");
 out.println("<BODY><H1>Session Snoop</H1>");
             out.println("You've visited this page " + count +
  ((count.intValue() == 1) ? " time." : " times."));
  out.println("<P>");
  out.println("<H3>Here is your saved session data:</H3>");
  String[] names = session.getValueNames();
  for (int i = 0; i < names.length; i++) {
  out.println(names[i] + ": " + session.getValue(names[i]) + "<BR>");
    }
    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + "<BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) +
                ")</I><BR>");
    out.println("Requested session ID from cookie: " +
                req.isRequestedSessionIdFromCookie() + "<BR>");
    out.println("Requested session ID from URL: " +
                req.isRequestedSessionIdFromUrl() + "<BR>");
    out.println("Requested session ID valid: " +
                 req.isRequestedSessionIdValid() + "<BR>");

    out.println("<H3>Here are all the current session IDs");
    out.println("and the times they've hit this page:</H3>");
    HttpSessionContext context = session.getSessionContext();
    Enumeration ids = context.getIds();
    while (ids.hasMoreElements()) {
      String id = (String)ids.nextElement();
      out.println(id + ": ");
      HttpSession foreignSession = context.getSession(id);
      Integer foreignCount =
        (Integer)foreignSession.getValue("snoop.count");
      if (foreignCount == null)
        out.println(0);
      else
        out.println(foreignCount.toString());
      out.println("<BR>");
     }
    out.println("</BODY></HTML>");
     }

}

No comments:

Post a Comment

Thanks for your valuable comments

Followers