by Dinesh Thakur

One of the ways to keep track of session between the client and the server is through the use of cookies. A cookie is a piece of information that a web server sends to the browser.



 
by Dinesh Thakur

HTTP is a stateless protocol; each time a client requests for a page, a separate connection is established between the client and the server. Thus, it provides no way for a server to maintain information for a particular user across multiple requests. There are many web applications where it is required to maintain this information. For example, in case of shopping cart, it is required to keep track of the list of items that are added in each user's cart. For this, the server must provide a way to store data for each client and distinguish clients from one another.



 
by Dinesh Thakur

In a web server, a session is a collection of all the requests made by a client (browser). HTTP is a stateless protocol. Between requests, it does not maintain any state of the client (browser). Suppose the client makes request for a web page, it should be checked whether the request is from an authorized user. It is impossible to check the authorization for each web page. It is necessary to maintain some information of the user while a user navigates between web pages. Thus, it is useful to maintain the state of client. The following processes arc used to maintain the state of a client:



 
by Dinesh Thakur

Usually the following four steps are followed while using sessions in servlets.

1. Accessing the Session object associated with the current request: In this step, invoke the getSession () method of the HttpServletRequest to return the HttpSession object.

 
by Dinesh Thakur

Cookies enable you to store the session information on the client side which has the following advantages,



 
by Dinesh Thakur

In order to read cookies that come back from the client (browser) in request header, you need to call getCookies () method of the HttpServletRequest. If the request contains no cookies this method returns null.

 
by Dinesh Thakur

Sending cookies to the client involves the following steps,

1. Create a Cookie object.

2. Setting the maximum age.

3. Placing the Cookie into the HTTP response headers.

 
by Dinesh Thakur

The Hypertext Transfer Protocol (HTTP) is the network protocol that the web servers and the client browsers use to communicate with each other. The HTTP is a stateless protocol. A client browser opens a connection and requests for a resource from the web server. The web server then responds with a requested resource and closes the connection.