0

If user1 enters below servlet the current time in milliseconds is added to a session variable. If user2 instantiates this servlet some time after user1 the session variable will be set to the new time. When user1 & user2 requests this session value each will have their own unique value? Will user2 overwrite user1 session val ?

    public void doGet(HttpServletRequest request, HttpServletResponse response) {

        request.getSession().setAttribute("time", System.currentTimeMillis());

        try {
            response.getWriter().print("Time is set");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
blue-sky
  • 51,962
  • 152
  • 427
  • 752
  • Servlet initialize only once in its lifetime i.e. `init() method` when requested for first time (if lazy load) and not for every request. The only method visible to request and response is `service(...)` - This method is called every time you made request. – RajeshS Jun 21 '11 at 09:36
  • 1
    Related: http://stackoverflow.com/questions/3106452/java-servlet-instantiation-and-session-variables – BalusC Jun 21 '11 at 11:39

4 Answers4

3

Each user will have their own session. Users will not be able to see each other's sessions (if they can, there is something seriously wrong with the system).

Edit (thanks to Richard H): The servlet container will automatically find the session for the current user by looking at the request; the request will contain a header or a cookie with the session ID, so that the container knows which user is doing the request.

Jesper
  • 202,709
  • 46
  • 318
  • 350
1

No, user2 will not overwrite user1's session value, because it has its own instance of the session. Wikipedia has a pretty good section on web sessions.

Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148
0

Both will have separate values. There will be 2 sessions for user1 & user2. User2 will not overwrite

isobar
  • 1,165
  • 8
  • 10
0

The Servlet Container manages user sessions. Each user receives a JSESSIONID which is a session ID that the browser (or user-agent) that sends the session ID to the servlet container for retrieval of the particular user.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228