Working with Session

In this tutorial, you will learn how to handle session in JSP by using session object.

HTTP protocol is stateless. It means that there is no permanent connection between the client (web browser) and Web Server. When a client requests a page from a web server, it opens a connection, retrieve the page and close connection. Web servers don’t know what happens then on the client side. In addition, If another request from a client is made, the web server doesn’t associate the new connection with the connection has been made.

In order to overcome the stateless of HTTP protocol, JSP provides you the implicit session object which is a HttpSession object. The session object resides on the server side so you can keep arbitrary data about the client and other data as well in session and later on in different requests you can retrieve the saved data for processing. JSP stores data on the server side in the session object by using a single key that client remembers.

The session object has the three most important methods which you use most as bellows:

Let’s take a look at an example how to use session object. In this example, we have three pages: In the first page, we collect data from the user, after that user submits the form to a second page which is used to store data in a session. In the last page, we get data back from the session and display it.

In the form above, when the user enters information, clicks submit button, the data goes through the page savetosession.jsp. In the  savetosession.jsp page, we save all the submitted data into the session object and forward the request to another page called  display.jsp page

As you see the code above, we use the  setAttribute() method to save data into the session object. Here is the page for displaying data in the session object:  display.jsp

The code is obvious, we used the  getAttribute() method of the  sessionobject to retrieve data which was entered in the form and displayed it on the page by using the expression.

How session works

When the server creates a new session, it always adds a session identifier in the form of a cookie. When the web browser asks for a page or makes a request, the web browser always sends a cookie which is created by the web server in the request. Therefore in the server side, web server checks for that cookie and find the corresponding session that is matched to the received cookie.

The session normally short-lived so the session cookie is not saved into the disk. Session also has a timeout. When the time is out, the session is no longer exist on the server side. You can set time out of session in the configuration file in the server.

  • Was this tutorial helpful ?
  • YesNo