servlets hits counter

‮gi.www‬iftidea.com

You can implement a simple hits counter in Servlets by using the HttpSession object to store a counter value. Here's an example of a Servlet that counts the number of times it has been accessed and displays the count on the page:

@WebServlet("/hits")
public class HitsCounterServlet extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession(true);
    Integer count = (Integer) session.getAttribute("count");
    if (count == null) {
      count = 1;
    } else {
      count++;
    }
    session.setAttribute("count", count);
    response.getWriter().println("This page has been accessed " + count + " times.");
  }
}

In this example, the Servlet retrieves the HttpSession object from the HttpServletRequest object using the getSession method. If the HttpSession object does not exist, a new one is created with the true argument.

The Servlet then retrieves the current count value from the HttpSession object using the getAttribute method. If the count value is null, the Servlet initializes it to 1. Otherwise, the Servlet increments the count value by 1.

The updated count value is then stored in the HttpSession object using the setAttribute method. Finally, the Servlet sends a response to the client that displays the current count value.