Servlet HttpSession

tutorial and example
tutorial and example

HttpSession is an interface used by servlet container to create a session between Http client and Http server. So using this interface we can maintain the state of a user.

The object of HttpSession stores various information about the user. This interface is present in javax.servlet.http package.

Methods of HttpSession

These are some important methods provided by HttpSession interface.

                 Methods

               Description

String getId()

This method returns a unique id of client used to identify it.

long getLastAccessedTime()

This method provides the time when last request is made. It returns the time in milliseconds.

Long getCreationTime()

This method provides the time when first request is made. It returns the time in milliseconds.

void setMaxInactiveInterval()

This method sets time in seconds after which the session becomes invalid.

Object getAttribute(String name)

This method provides the value of attribute bind with the name passed within it.

Example of HttpSession

In this example, we will maintain the state of a particular client. When a client makes first request then its unique id is generated. With each request, number of visit of a user is incremented by one unless request will be made within a specific period of time given in setMaxInactiveInterval() method unless the session becomes expire.

HttpSessionExample.java

Output: