/*
* This example is from the book "Java Enterprise in a Nutshell".
* Copyright (c) 1999 by O'Reilly & Associates.
* You may distribute this source code for non-commercial purposes only.
* You may study, modify, and use this example for any purpose, as long as
* this notice is retained. Note that this example is provided "as is",
* WITHOUT WARRANTY of any kind either expressed or implied.
*/
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class VisitCounterServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter out = resp.getWriter();
resp.setContentType("text/html");
HttpSession thisUser = req.getSession(true);
Integer visits;
if(!thisUser.isNew()) { //Don't check newly created sessions
visits = (Integer)thisUser.getValue("visitcounter.visits");
if(visits == null)
visits = new Integer(1);
else
visits = new Integer(visits.intValue() + 1);
}
else
visits = new Integer(1);
// Put the new count in the session
thisUser.putValue("visitcounter.visits", visits);
// Finally, display the results and give them the session ID too
out.println("<HTML><HEAD><TITLE>Visit Counter</TITLE></HEAD>");
out.println("<BODY>You have visited this page " + visits + " time[s]");
out.println("since your last session expired.");
out.println("Your Session ID is " + thisUser.getId());
out.println("</BODY></HTML>");
}
}
|