Avatar ·

How servlets work: creation, sessions, shared variables and multithreading

Hello everyone! I've just started learning Java EE and servlets, but I'm confused about some fundamental things. Can you explain in simple terms?\n\nI have a simple servlet that counts page visits. I expected each user to see their own counter, but in reality it works strangely.\n\nHere's my code:\n\n```java\npublic class CounterServlet extends HttpServlet {\n private int counter = 0;\n\n protected void doGet(HttpServletRequest request, HttpServletResponse response) \n throws ServletException, IOException {\n counter++;\n response.getWriter().println("You have visited this page " + counter + " time(s)");\n }\n}\n```\n\nI opened it in two different browsers (Chrome and Firefox). In the first browser I refreshed the page 3 times — the counter showed