简体   繁体   中英

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

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 confusions surrounding the HttpServletRequest and HttpServletResponse objects and how they can be used to add headers to the request and response objects and how they relate to sessions.

As far as I understand, a cookie is a type of header just like Content-type and Accept. The java servlet api just makes it easy to work with the header by using methods specific to the context in which the header is being used. For example:

response.setContentType(String mimeType)
response.setContentLength(int lengthInBytes)

My confusion starts here.. Cookie is not a String or int, its a object:

response.addCookie(Cookie cookie)
response.getCookies()

Since a cookie is a type of header, can't I just use something like this:

String cookieVal = response.getHeader("cookie")

I'm having difficulty understanding session management and how it relates to the HttpServletRequest and HttpServletResponse API.. What is the HttpSession object for?

HttpSession.getAttribute() // What is this getting??
HttpSession.setAttribute("Bla Bla", "valuetoset") // What is this setting?

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.

You are correct that cookies are managed using headers. There are TWO cookie management related headers: Cookie and Set-Cookie .

Cookie header is sent by the user agent (browser) and will be available in your HttpServletRequest object and the Set-Cookie header is appended to your HttpServletResponse object when you use methods such as addCookie(Cookie) .

In Java an HttpSession is established when the first request reaches your application. The Servlet Spec implementation in your container (Jetty, Tomcat, WebSphere, etc) will create and manage the HttpSession. The browser will receive a JSESSIONID cookie which will identify this particular session in the future.

Agreeing with the answers given above, I would like to conclude that Cookie and Session are two different entities in the world of web.

Cookie

Cookie represents some brief information that's generated by server and stored on client(browser). According to HTTP mechanism, browser have to send all the cookies(that have not expired), that server had sent before to browser.

Session

HTTP is a stateless protocol. Unlike FTP and other protocol, where connection state is preserved between multiple request-response transaction, in HTTP connection is established for one request and it's closed when response for that request is satisfied. This flaw in HTTP is present, because it was designed in early days to serve static web pages only. But as web has expanded, it's now used to serve dynamic full-fledged webapps. Thus, it has become necessary to identify users. Thus, for every request served by web-server, a labeling mechanism is required which can identify user of each request. This identification of user of request(whether the request has came from same user, same machine), sessions are used.
Session can be successfully implemented only if web-server can receive any information about the user in the request. One way of making this information available to user is Cookie. Others are URL rewriting, hidden fields, etc.

session.setAttribute() will store information in current session on server side not on client side(browser).

Hope it may help you.

Ok Looks like you want to see the difference between Cookies and Headers. They have different purpose. Cookies are temporary storage of information on client side. Server set the cookies(data) on the response and once set browser send these cookies(data) with each subsequent requests till the cookie expires . But headers are used as hints to browser and server. For ex

setHeader("Content-Type", "application/json");

will inform client to prepare to see a json response in the payload. Since it is a "one time" information there is not need the browser to send that information back to the server with each new requests like cookies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM