Confusion about how java web session handeling works. Demystifying Cookies and Header differences using servlet api and HttpSession object

前端 未结 4 583
滥情空心
滥情空心 2020-12-08 17:50

I am learning Spring security and Spring MVC, but I realized I needed to learn jsp Servlets first and general web programming in a java environment.

I have confusio

4条回答
  •  被撕碎了的回忆
    2020-12-08 18:29

    You can read the RFC describing Cookies and the related headers, Set-Cookie and Cookie to understand what they are.

    You can go through Chapter 7 of the Servlet Specification if you want to understand in detail how Cookies and Sessions are related.

    You first need to understand that HTTP is a stateless protocol. This means that each request that a client makes has no relation to any previous or future requests. However, as users, we very much want some state when interacting with a web application. A bank application, for example, only wants you to be able to see and manage your transactions. A music streaming website might want to recommend some good beats based on what you've already heard.

    To achieve this, the Cookie and Session concepts were introduced. Cookies are key-value pairs, but with a specific format (see the links). Sessions are server-side entities that store information (in memory or persisted) that spans multiple requests/responses between the server and the client.

    The Servlet HTTP session uses a cookie with the name JSESSIONID and a value that identifies the session.

    The Servlet container keeps a map (YMMV) of HttpSession objects and these identifiers. When a client first makes a request, the server creates an HttpSession object with a unique identifier and stores it in its map. It then adds a Set-Cookie header in the response. It sets the cookie's name to JSESSIONID and its value to the identifier it just created.

    This is the most basic Cookie that a server uses. You can set any number of them with any information you wish. The Servlet API makes that a little simpler for you with the HttpServletResponse#addCookie(Cookie) method but you could do it yourself with the HttpServletResponse#addHeader(String, String) method.

    The client receives these cookies and can store them somewhere, typically in a text file. When sending a new request to the server, it can use that cookie in the request's Cookie header to notify the server that it might have done a previous request.

    When the Servlet container receives the request, it extracts the Cookie header value and tries to retrieve an HttpSession object from its map by using the key in the JSESSIONID cookie. This HttpSession object is then attached to the HttpServletRequest object that the Servlet container creates and passes to your Servlet. You can use the setAttribute(String, Object) and getAttribute(String) methods to manage state.

提交回复
热议问题