Servlet Session Creation Last Access Time : Session « Servlet « Java Tutorial






import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.text.DateFormat;
public class MyServlet extends HttpServlet {
   
 public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        Date creationTime = new Date(session.getCreationTime() );
        Date lastAccessed = new Date(session.getLastAccessedTime());
        Date now = new Date();
        DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM);
        
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Displaying the Session Creation and Last-Accessed Time</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h2>Session Creation and Last-Accessed Time</h2>");
        out.println("The time and date now is: " + formatter.format(now) + "<br><br>");
        out.println("The session creation time: HttpSession.getCreationTime( ): " + formatter.format(creationTime) + "<br><br>");
        out.println("The last time the session was accessed: HttpSession.getLastAccessedTime( ): " + formatter.format(lastAccessed) );
        out.println("</body>");
        out.println("</html>");
        
        
    }
}
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
    <servlet><servlet-name>MyServletName</servlet-name>
             <servlet-class>MyServlet</servlet-class>

             
    </servlet>
    
    <servlet-mapping><servlet-name>MyServletName</servlet-name>
        <url-pattern>/index.html</url-pattern>
    </servlet-mapping>
</web-app>
  Download:  ServletSessionCreationLastAccessTime.zip( 89 k)








25.5.Session
25.5.1.Servlet Session Info
25.5.2.Servlet Session Snoop
25.5.3.Servlet Session Max Inactive Interval
25.5.4.Servlet Session Creation Last Access Time
25.5.5.Servlet Session Check
25.5.6.Get Set Session Value in a Servlet
25.5.7.Get Set SessionAttributes in Servlet
25.5.8.use the Servlet API to manage session information
25.5.9.Session Events