0

I am trying to make a servlet thread-safe by synchronizing a block of code.The counter needs to count how many times a page has been visited.But it starts at 2 and when i refresh the page, it increments by 2(so it goes 2,4,6).I tried to remove the object variable while preserving the functionality but to no avail.what is missing in my code?
here is my servlet:

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


public class Count extends HttpServlet 
{
   
   private int visitCount = 0;

    protected  void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {

        synchronized(this){
        visitCount++;
        
        request.setAttribute("counter", visitCount);
      
    }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    
    public String getServletInfo()
    {
        return "Short description";
    }// </editor-fold>
}
2
Contributors
1
Reply
4
Views
6 Years
Discussion Span
Last Post by Taywin
0

It looks like it is calling processRequest twice. Could you try and change your doPost() to...

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doGet(request, response);
}

and you may need to declare visitCount as static?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.