7

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?
Horse Voice
  • 8,138
  • 15
  • 69
  • 120

4 Answers4

14

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 1
    So I'm trying to understand this in http standard response or request terms. There are several keys in a request header such as Accept, Content-type... And these keys have values such as `"Application/json"` etc.. So what does the header key named cookie contain? Does it contain `"JSESSIONID=3894839849328"` or something like that? Or is there a new key of the header created called `JSESSIONID` that is just referred to as the cookie? In that case, every header key is a cookie. – Horse Voice Nov 11 '13 at 00:53
  • @TazMan On the first request, the `Servlet` container will respond with a header like `Set-Cookie:JSESSIONID=0444B0FEFC39BC52343C4DE6AB2AF492; Path=/so/; HttpOnly`. The client can then send the header `Cookie:JSESSIONID=0444B0FEFC39BC52343C4DE6AB2AF492` to identify its user. On chrome, you can press `F12` to and look at the network tab to see header values for each request the browser makes. – Sotirios Delimanolis Nov 11 '13 at 01:21
  • Thank you. So the Set-Cookie is a header attribute sent by the server. And Cookie is the header attribute sent by the client to the server right? – Horse Voice Nov 11 '13 at 01:38
  • If you could confirm my logic to conclude this please: If I have some code like this: `HttpSession session = request.getSession();` and then have `session.setAttribute("productCode", product.getCode());`and add another attribute to the session like this: `session.setAttribute("productName", product.getName());` The Cookie header in the http request will be: `cookie: productCode=somecode; productName=someName`.. Right? – Horse Voice Nov 11 '13 at 01:52
  • 2
    @TazMan No. The session attributes have nothing to do with the `Cookie`. The attributes are stored and managed server side. They are never returned to the client in a header. This is how the server manages state. – Sotirios Delimanolis Nov 11 '13 at 01:52
  • I'm so lost.. Still trying to understand a lot of what you mentioned in your answer. See I'm completely new to web development. I understand statelessness and headers.. I don't understand cookies and how java handles them. HttpSession is used to work with cookies and manage state.. – Horse Voice Nov 11 '13 at 01:59
  • @TazMan We use HTTP headers to transmit cookies. Because cookies usually hold much more information than a typical header, the `Servlet` API offers a few classes and methods to simplify the task of reading them from a request adding them to a response. Read the various articles linked in my answers. They are long but very informative. – Sotirios Delimanolis Nov 11 '13 at 02:03
2

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.

Community
  • 1
  • 1
Strelok
  • 50,229
  • 9
  • 102
  • 115
  • Can you give an example of what values the 2 header keys would contain? `Cookie` key of the header and the `Set-Cookie` of the header. These would be header keys just like Accept and Content-type right?? As I understand it, a response or a request contains a list of key-value pairs. Like this: `(headername: headervalue)` – Horse Voice Nov 11 '13 at 00:56
1

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.

Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97
0

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.

Upul Doluweera
  • 2,146
  • 1
  • 23
  • 28