/* * @(#)CounterRewrite.java * * Copyright (c) 1998 Karl Moss. All Rights Reserved. * * You may study, use, modify, and distribute this software for any * purpose provided that this copyright notice appears in all copies. * * This software is provided WITHOUT WARRANTY either expressed or * implied. * * @author Karl Moss * @version 1.0 * @date 20Jan99 * */ package javaservlets.session; import javax.servlet.*; import javax.servlet.http.*; /** *

This is a simple servlet that uses session tracking * and URL rewriting to count the number of times a client session * has accessed this servlet. */ public class CounterRewrite extends HttpServlet { // Define our counter key into the session static final String COUNTER_KEY = "CounterRewrite.count"; /** *

Performs the HTTP GET operation * * @param req The request from the client * @param resp The response from the servlet */ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException { // Set the content type of the response resp.setContentType("text/html"); // Get the PrintWriter to write the response java.io.PrintWriter out = resp.getWriter(); // Get the session HttpSession session = req.getSession(true); // Is there a count yet? int count = 1; Integer i = (Integer) session.getValue(COUNTER_KEY); // If a previous count exists, set it if (i != null) { count = i.intValue() + 1; } // Put the count back into the session session.putValue(COUNTER_KEY, new Integer(count)); // Print a standard header out.println(""); out.println(""); out.println("Session Counter " + "with URL rewriting"); out.println(""); out.println(""); out.println("Your session ID is " + session.getId()); out.println(" and you have hit this page " + count + " time(s) during this browser session"); // Format the URL String url = req.getRequestURI(); //+ ";" + SESSION_KEY + //session.getId(); out.println("

"); out.println(""); out.println("
"); // Wrap up out.println(""); out.println(""); out.flush(); } /** *

Performs the HTTP GET operation * * @param req The request from the client * @param resp The response from the servlet */ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException { // Same as get request doGet(req, resp); } /** *

Initialize the servlet. This is called once when the * servlet is loaded. It is guaranteed to complete before any * requests are made to the servlet * * @param cfg Servlet configuration information */ public void init(ServletConfig cfg) throws ServletException { super.init(cfg); } /** *

Destroy the servlet. This is called once when the servlet * is unloaded. */ public void destroy() { super.destroy(); } }