What is session management in Java?

后端 未结 6 1261
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-23 18:20

I have faced this question in my Interview as well. I do have many confusion with Session Scope & it management in java.

In web.xml we do have the entry :

<
6条回答
  •  感动是毒
    2020-12-23 18:32

    Session management is not something limited to Java and servlets. Here's roughly how it happens:

    1. The HTTP protocol is stateless, so the server and the browser should have a way of storing the identity of the user through multiple requests
    2. The browsers sends the first request to the server
    3. The server checks whether the browser has identified with the session cookie (see below)

      3.1. if the server doesn't 'know' the client:

      • the server creates a new unique identifier, and puts it in a Map (roughly), as a key, whose value is the newly created Session. It also sends a cookie response containing the unique identifier.

      • the browser stores the session cookie (with lifetime = the lifetime of the browser instance), containing the unique identifier, and uses it for each subsequent request to identify itself uniquely.

      3.2. if the server already knows the client - the server obtains the Session corresponding to the passed unique identifier found in the session cookie

    Now onto some the questions you have:

    • the session timeout is the time to live for each session map entry without being accessed. In other words, if a client does not send a request for 30 minutes (from your example), the session map will drop this entry, and even if the client identifies itself with the unique key in the session cookie, no data will be present on the server.

    • different gmails (and whatever site) can be opened in different browsers because the session cookie is per-browser. I.e. each browser identifies itself uniquely by either not sending the unique session id, or by sending one the server has generated for it.

    • logging from different PCs is the same actually - you don't share a session id

    • logging-out is actually removing the entry for the session id on the server.

    Note: the unique session id can alternatively be stored:

    • in a cookie
    • in the URL (http://example.com/page;JSESSIONID=435342342)
    • 2 or 3 other ways that I don't recall and aren't of interest

提交回复
热议问题