HttpSession Example Hit Count

HttpSession Example Hit Count

HttpSession Example on Visitor Hit Count

After learning Session, Session tracking, Session ID and HttpSession and its methods, let us write a program to maintain session tracking using HttpSession interface.

The aim of this code is, in a single session, the user visits the site (HitCount servlet) by clicking the submit button number of times. Everytime, the existing hit count number is incremented and the value is stored with session object.

HttpSession Example

Following is the client file: HitCount.html

HitCount servlet web.xml entry

HttpSession session = req.getSession();

The getSession() method of HttpServletRequest returns an object of HttpSession.

Integer hitNumber = (Integer) session.getAttribute("rama");

To store the values of the session, the values are binded with the session object with setAttribute() and retrieved later with getAttribute(), defined in HttpSession interface. When the first time the user calls the HitCount servlet, the getAttribute("rama") returns null as no value on the key rama was set to the session object earlier (as first time the servlet is called).

session.setAttribute("rama", hitNumber);

The value of hitNumber is attached to the session object with key rama using setAttribute() method. The parameters of setAttribute() are – the first parameter is always a string and the second one should be an object of any Java class.

if(hitNumber == null)
hitNumber = new Integer(1);

In the first visit, the hitNumber is null and thereby if condition is executed. Here, the hitNumber is given with the value 1.

In the subsequent visits, the hitNumber is not null as with setAttribute(), the hitNumber is set with key rama and thereby else condition is executed. The if condition is executed only once.

hitNumber = new Integer(hitNumber.intValue()+1) ;

getId() returns the session ID, getCreationTime() returns the session creation time and getLastAccessedTime() returns the latest accessed time. These methods are more explained in HTTP Session, HttpSession Methods.

HttpSession Example
Output screen on HttpSession Example: HTML file with Submit button "GET HITS"

HttpSession Example
Output screenshot on HttpSession Example when user clicked 5 times

At any time the session can be closed with session.invalidate() method. The invalidate() method invalidates the current session and when invalidated, the session object is destroyed (and thereby the data attached with the session is also lost).

Let us see how to call invalidate(). Suppose think, after 100000 hits, you would like to start again the session count.

if(hitNumber == 100000)

Now the session object is garbage collected and no more session. When you call again, a fresh session object is created with new ID and new data.

Leave a Reply

Your email address will not be published. Required fields are marked *