Get and Set Session Variables in a Servlet

This code example shows how to set and get variables stored in a session. To get a reference to the session object we call the getSession() method of the HttpServletRequest object.
We send the argument true to the method to tell it to create the session if it doesn’t exist.
Then we try to get the session variable ‘VisitCounter’ from the session by calling the method getAttribute().
It’s supposed to be stored as an Integer object, so we cast it to an Integer directly.
If the parameter is null, we create a new Integer object with the value of one (1) and add it to the session, else we add one to the object retrieved from the session and write it back to the session again. When writing a variable to the session the method setAttribute() is used.
Then we print out the value of the session parameter, which tells how many times this page has been displayed during this particular session.

This is what the text will look like if you hit the refresh button a few times:

Search for more Java info on this site here:
Custom Search

Please type any questions here.