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

/**
 * The URLSessionServlet demonstrates how the servlet API
 * makes it easy to use rewritten URLs for session
 * management rather than cookies.
 *
 * @author Dustin R. Callaway
 * @version 1.0, 08/08/98
 */
public class URLSessionServlet extends HttpServlet
{
  /**
   * init method is called when servlet is first loaded.
   */
  public void init(ServletConfig config) throws    ServletException
  {
    super.init(config); //pass ServletConfig to parent
  }


  /**
   * service uses session object to track the number of times
   * each user has requested this servlet.
   */
  public void service(HttpServletRequest request,
    HttpServletResponse response) throws ServletException,
    IOException
  {
    //get current session or, if necessary, create a new one
    HttpSession mySession =    request.getSession(true);

    //get hit count from session
    Integer count = (Integer)mySession.getValue("hitCounter");

    if (count == null) //hitCounter value not in session
    {
      count = new Integer(1); //start hit count at 1
    }
    else //session contains hitCounter
    {
      //increment hit counter
      count = new Integer(count.intValue() + 1);
    }
    //store hit count in session
    mySession.putValue("hitCounter", count);

    //MIME type to return is HTML
    response.setContentType("text/html");

    //get a handle to the output stream
    PrintWriter out = response.getWriter();

    //generate HTML document to send to client
    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>Sessions with URLs</TITLE>");
    out.println("</HEAD>");
    out.println("<BODY>");
    out.println("You have visited this page " + count +
      " times.<P>");

    out.println("Click <A HREF=\"" +
      response.encodeUrl("URLSessionServlet") +
      "\">here</A> to load page again.");

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

    out.close(); //close output stream
  }

  /**
   * getServletInfo returns a brief description of this servlet
   */
  public String getServletInfo()
  {
    return "Manages session with rewritten URLs.";
  }
}