Tuesday, 30 August 2011

ExampleSessionServlet Program

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

public class ExampleSessionServlet extends HttpServlet
{
      public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
    {
            HttpSession session = request.getSession(true);
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            String title = "Simple Session Servlet Example";
            Integer accessCount = new Integer(0);

            if (session.isNew())
        {
            }
        else
        {
                  Integer oldAccessCount = (Integer)session.getValue("accessCount");
                  if (oldAccessCount != null)
            {
                  accessCount = new Integer(oldAccessCount.intValue() + 1);
                  }
            }
            session.putValue("accessCount", accessCount);
     
            out.println(title + "<BODY BGCOLOR=\"#FDF5E6\">\n" +
                            "<H2>Information on Your Session:</H2>\n" +
                            "<TABLE BORDER=1 ALIGN=CENTER>\n" +
                            "<TR BGCOLOR=\"#FFAD00\">\n" +
                            "  <TH>Info Type<TH>Value\n" +
                            "<TR>\n" +
                            "  <TD>ID\n" +
                            "  <TD>" + session.getId() + "\n" +
                            "<TR>\n" +
                            "  <TD>Creation Time\n" +
                            "  <TD>" + new Date(session.getCreationTime()) + "\n" +
                            "<TR>\n" +
                            "  <TD>Time of Last Access\n" +
                            "  <TD>" + new Date(session.getLastAccessedTime()) + "\n" +
                            "<TR>\n" +
                            "  <TD>Number of Previous Accesses\n" +
                            "  <TD>" + accessCount + "\n" +
                            "</TABLE>\n" +
                            "</BODY></HTML>");
      }
    /* By using getCreationTime() and new Date().getTime() you can set timeouts
    * for the session. If you are using JSDK 2.2 or higher then you can use
    * setMaxInactiveInterval(int interval) for setting timeouts.
    */
}

No comments:

Post a Comment