Sponsered Links
Categories
Sponsered Links

Servlet session creation time, session accessed time, and session id

 

This example illustrates how to find the session creation time, session accessed time, and session id of servlet.

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

public class SessionServlet extends HttpServlet {
    public void doGet (HttpServletRequest req, HttpServletResponse res)    throws ServletException, IOException {
        HttpSession session = req.getSession(true);
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        pw.println("<head><title> " + "SessionServlet Output " + "</title></head><body>");
        pw.println("<h1> SessionServlet Output </h1>");
        Integer ival = (Integer) session.getAttribute("sessionservlet.counter");
        if (ival == null) {
            ival = new Integer(1);
        } else {
            ival = new Integer(ival.intValue() + 1);
        }
        session.setAttribute("sessionservlet.counter", ival);
        pw.println(" You have hit this page <b>" + ival + "</b> times.<p>");
        pw.println("Click <a href=" + res.encodeURL(HttpUtils.getRequestURL(req).toString()) + ">here</a>");
        pw.println(" to ensure that session tracking is working even " + "if cookies aren't supported.<br>");
        pw.println("Note that by default URL rewriting is notenabled" + " due to its large overhead.");
        pw.println("<h3>Request and Session Data</h3>");
        pw.println("Session ID in Request: " + req.getRequestedSessionId());
        pw.println("<br>Session ID in Request is from a Cookie: " + req.isRequestedSessionIdFromCookie());
        pw.println("<br>Session ID in Request is from the URL: " + req.isRequestedSessionIdFromURL());
        pw.println("<br>Valid Session ID: " + req.isRequestedSessionIdValid());
        pw.println("<h3>Session Data</h3>");
        pw.println("New Session: " + session.isNew());
        pw.println("<br> Session ID: " + session.getId());
        pw.println("<br> Creation Time: " + new Date(session.getCreationTime()));
        pw.println("<br>Last Accessed Time: " + new Date(session.getLastAccessedTime()));
        pw.println("</body>");
        pw.close();
    }

    public String getServletInfo() {
        return "A simple session servlet";
    }
}

 
 
Sponsered Links
Latest Updates
 
All Content of this site is for learning only. We do not warrant the correctness of its content. The risk from using it lies entirely with the user. While using this site, you agree to have read and accepted our terms of use and privacy policy.
Copyright © 2009 JSPSERVLETTUTORIAL.INFO All Right Reserved