Hope the sample code can help you:
Simple counter
To demonstrate the life cycle of a servlet, we start with a simple example. Example 3-1 shows a servlet that counts and displays the number of calls to it. For simplicity, it displays plain text.
Example 3-1. Simple counter
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SimpleCounter extends HttpServlet { int count = 0; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Since loading, this servlet has been accessed " + count + " times."); } }
Otherwise, if you want something more advanced, a good option is to use a holistic counter:
Example 3-2 Holistic counter
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class HolisticCounter extends HttpServlet { static int classCount = 0;
This HolisticCounter tracks its own access account using the instance variable count, the total counter with the class variable classCount, and the number of instances with hashtable instances (another shared resource, which should be a class variable).
Ref. Java Servlet Programming by Jason
Avanz
source share