A session as you probably mean it is a server-side object which stores state. You use it in servlets to store and retrieve data.
A cookie is a small piece of information a browser sends to a server with every request.
- A cookie can keep information in the user’s browser until deleted. If a person has a login and password, this can be set as a cookie in their browser so they do not have to re-login to your website every time they visit. You can store almost anything in a browser cookie.
- The trouble is that a user can block cookies or delete them at any time. If, for example, your websites shopping cart utilized cookies, and a person had their browser set to block them, then they could not shop at your website.
- Sessions are not reliant on the user allowing a cookie. They work instead like a token allowing access and passing information while the user has their browser open. The problem with sessions is that when you close your browser you also lose the session. So, if you had a site requiring a login, this couldn’t be saved as a session like it could as a cookie, and the user would be forced to re-login every time they visit.
Most servlet containers use a cookie to identify a session.
1) The user’s browser requests a servlet.
2) The servlet container creates a session.
3) The servlet gives the session a unique ID.
4) The servlet sets a cookie in the browser with this ID.
5) Let’s say the servlet then store’s the user’s name in
the session.
5) The user requests another servlet on the same server.
As part of the request, the cookie with the session ID
is sent back to the server.
6) Since the servlet container is told which session to use,
it make it available again.
7) So servlet #2 can retrieve the user’s name, since we
put it in the session, and say, “Hi, Anand.”
cookies are only simple text that is stored on the client with some useful data to identify subsequent requests from the client and help the server to serve the client efficiently. cookies can hold data like books bought during an http session until the session expires. if you could store the nature of these books (e.g. fiction, technology etc.) then this data could be used to know the browsing behaviour of the user.
Sessions are objects (not text files) that store data and regarding a particular session and help the servlets to transfer this data to other servlet invocation so that the WEB SERVER understands (or is made to understand) that these requests have come from the same client. e.g. HttpSession objects are used to store such information.