Signup · Login
Stardeveloper.com  
Home · Tutorials · Forums · Web Hosting Plans · Faisal Khan's Blog · Contact
Search Stardeveloper.com
Stardeveloper RSS Feed
Newsletter
Enter your email address below to be informed every time a new article is posted at Stardeveloper.com:

You can follow Faisal Khan on Twitter
Article Categories
.NET  .NET
  ASP (16)
  ASP.NET (41)
  ADO (16)
  ADO.NET (10)
  COM (6)
  Web Services (4)
  C# (1)
  VB.NET (3)
  IIS (2)

J2EE  J2EE
  JSP (15)
  Servlets (9)
  Web Services (1)
  EJB (4)
  JDBC (4)
  E-Commerce (1)
  J2ME (1)
  Products (1)
  Applets (1)
  Patterns (1)
Log In
UserName Or Email:

Password:

Auto-Login:

Miscellaneous Links
  Submit Article

Hosted by Securewebs.com
 
Home : J2EE : Servlets : Managing Sessions with Java Servlets
 

Managing Sessions with Java Servlets

by Faisal Khan.Follow Faisal Khan on Twitter

Overview
In this article we are going to talk about another wonderful aspect of web application development; managing sessions. I have already talked about installing Java application server and basics about Servlets. If you have been following my earlier articles then building Servlets shouldn't be a problem for you, all it takes is creating a Java class and extending from HttpServlet class and overriding a couple of methods. If you are not comfortable with Servlets then I would suggest that you consider going through some of the basic articles in the ' JSP and Servlets' section.

What is a Session ?
A session is pretty much what it sounds, when a user makes a page request to the server, the server creates a temporary session to identify that user. So when that same user goes to another page on that site, the server identifies that user. So a session is a small and temporary unique connection between a server and the user enabling it to identify that user across multiple page requests or visits to that site.

What is Session Management ?
Ok now you know what is a session. Session management is to use the API provided by your application server to identify the user across multiple page requests. Note that every server has it's own set of API for session management, since we are talking about 'Managing Sessions with Java Servlets', we will be making use of the Servlet API 2.2 which almost all of the Java application servers support.

Why use Session Management ?
Hundreds and thousands of simultaneous users can be visiting your site and if you can identify each of them separately then it can provide tremendous benefits to you. Following are only some of the uses which have come to my mind :

  • Customizations : Your can allow site visitors to customize the look and feel of your site, thus show each user a different view of your site. You can also show different content to different users depending on their preferences. I am also thinking about adding customization features to Stardeveloper.com which will allow you to change the layout, color schemes, fonts etc according to your own liking.
  • Security : You can allow membership based access to  your site thus making sure that only members get to see special content on your site. After logging in you can identify members from non-members by setting an attribute on the user session to some value. Thus no need to log in again and again.
  • User Behavior : You can log user behavior like how many ad views have been shown to the user. If lot have been shown with no response from the user then it is time to change that ad. This is a great feature really, if you are into making an ad rotation software you can count how many ad views of which advertiser have been shown to the user and if user doesn't click through then better change that ad with some other one instead of wasting ad views of the same ad on this user.

These are only some of the important ones which come to mind. Ok, we now know what is a session and what use session management may be to us. From next page onwards we will learn the Servlet API interface required for session management and you will be surprised to know that there is only one interface involved, simple!.

Following is a list of topics we'll cover in this article :

HttpSession Interface
Managing sessions has been made extremely easy by the Servlet API since there is just a single interface involved and that interface is HttpSession interface. You then invoke methods of this interface to interact with the user.

Methods of HttpSession Interface
Before going into the details of using different methods of this interface, lets first see what are different methods available to us.

  • getAttribute(), getAttributeNames(), setAttribute(), removeAttribute() These methods are used to set, get and remove objects from a user session. We will see later how to use them.
  • getId() Every session created by the server has a unique 'id' associated with it in order to identify this session from other sessions. This method returns the 'id' of this session.
  • getCreationTime() Simple returns a long value indicating the date and time this session was created, meaning there by that you get the time this user first accessed your site.
  • getLastAccessedTime() Returns a long value indicating the last time user accessed any resource on this server.
  • getMaxInactiveInterval(), setMaxInactiveInterval() Return and set the maximum inactive interval in seconds for this session respectively. Note that every session has a maximum inactive interval during which if user doesn't make request to the server, his session is invalidated.
  • isNew() Returns a boolean value indicating if the session is new. It means that either it is the first page of the site user has hit so his session is new and has just been created or that user is not accepting cookies required for managing sessions so this value will then always return true.
  • invalidate() Simply invalidates a session. You can use this method on a 'logout' page allowing user to end his session. If after invalidation of his session user accesses some resource on the site then a new session will be created for it. You must have seen this 'logout' feature which ends your session on some of the free email sites on the web, so you understand how useful this method is.

It is time now to actually build an example Servlet which demonstrates the methods we just learned. This is what we are going to do on the next page, build a simple Servlet which will track number of times this Servlet has been seen by the user. In this example you will also learn how to bind objects to a user session, this is very important as most often than not you will be working with session level objects. Enough said, lets move on to the next page now.

Session Demo Application
The application we are going to build will demonstrate the use of almost all of the methods of HttpSession interface we discussed on the last page. We haven't yet built the application but you can see the session Servlet demo here. This way you know what kind of application we are going to make. Don't forget to refresh the page of Servlet above since only that way you can appreciate the page count incrementing.

Overview of the Demo Application
We will first build a simple Java class 'Counter'. This class will be responsible for keeping count of pages viewed by the user. We will then build a Servlet which will use HttpSession.setAttribute() method to bind this Counter object to the user session. So every user will have a different session and thus every session will have a different Counter object attached to it.

Overview
In this article we are going to talk about another wonderful aspect of web application development; managing sessions. I have already talked about installing Java application server and basics about Servlets. If you have been following my earlier articles then building Servlets shouldn't be a problem for you, all it takes is creating a Java class and extending from HttpServlet class and overriding a couple of methods. If you are not comfortable with Servlets then I would suggest that you consider going through some of the basic articles in the ' JSP and Servlets' section.

What is a Session ?
A session is pretty much what it sounds, when a user makes a page request to the server, the server creates a temporary session to identify that user. So when that same user goes to another page on that site, the server identifies that user. So a session is a small and temporary unique connection between a server and the user enabling it to identify that user across multiple page requests or visits to that site.

What is Session Management ?
Ok now you know what is a session. Session management is to use the API provided by your application server to identify the user across multiple page requests. Note that every server has it's own set of API for session management, since we are talking about 'Managing Sessions with Java Servlets', we will be making use of the Servlet API 2.2 which almost all of the Java application servers support.

Why use Session Management ?
Hundreds and thousands of simultaneous users can be visiting your site and if you can identify each of them separately then it can provide tremendous benefits to you. Following are only some of the uses which have come to my mind :

  • Customizations : Your can allow site visitors to customize the look and feel of your site, thus show each user a different view of your site. You can also show different content to different users depending on their preferences. I am also thinking about adding customization features to Stardeveloper.com which will allow you to change the layout, color schemes, fonts etc according to your own liking.
  • Security : You can allow membership based access to  your site thus making sure that only members get to see special content on your site. After logging in you can identify members from non-members by setting an attribute on the user session to some value. Thus no need to log in again and again.
  • User Behavior : You can log user behavior like how many ad views have been shown to the user. If lot have been shown with no response from the user then it is time to change that ad. This is a great feature really, if you are into making an ad rotation software you can count how many ad views of which advertiser have been shown to the user and if user doesn't click through then better change that ad with some other one instead of wasting ad views of the same ad on this user.

These are only some of the important ones which come to mind. Ok, we now know what is a session and what use session management may be to us. From next page onwards we will learn the Servlet API interface required for session management and you will be surprised to know that there is only one interface involved, simple!.

Following is a list of topics we'll cover in this article :

HttpSession Interface
Managing sessions has been made extremely easy by the Servlet API since there is just a single interface involved and that interface is HttpSession interface. You then invoke methods of this interface to interact with the user.

Methods of HttpSession Interface
Before going into the details of using different methods of this interface, lets first see what are different methods available to us.

  • getAttribute(), getAttributeNames(), setAttribute(), removeAttribute() These methods are used to set, get and remove objects from a user session. We will see later how to use them.
  • getId() Every session created by the server has a unique 'id' associated with it in order to identify this session from other sessions. This method returns the 'id' of this session.
  • getCreationTime() Simple returns a long value indicating the date and time this session was created, meaning there by that you get the time this user first accessed your site.
  • getLastAccessedTime() Returns a long value indicating the last time user accessed any resource on this server.
  • getMaxInactiveInterval(), setMaxInactiveInterval() Return and set the maximum inactive interval in seconds for this session respectively. Note that every session has a maximum inactive interval during which if user doesn't make request to the server, his session is invalidated.
  • isNew() Returns a boolean value indicating if the session is new. It means that either it is the first page of the site user has hit so his session is new and has just been created or that user is not accepting cookies required for managing sessions so this value will then always return true.
  • invalidate() Simply invalidates a session. You can use this method on a 'logout' page allowing user to end his session. If after invalidation of his session user accesses some resource on the site then a new session will be created for it. You must have seen this 'logout' feature which ends your session on some of the free email sites on the web, so you understand how useful this method is.

It is time now to actually build an example Servlet which demonstrates the methods we just learned. This is what we are going to do on the next page, build a simple Servlet which will track number of times this Servlet has been seen by the user. In this example you will also learn how to bind objects to a user session, this is very important as most often than not you will be working with session level objects. Enough said, lets move on to the next page now.

Session Demo Application
The application we are going to build will demonstrate the use of almost all of the methods of HttpSession interface we discussed on the last page. We haven't yet built the application but you can see the session Servlet demo here. This way you know what kind of application we are going to make. Don't forget to refresh the page of Servlet above since only that way you can appreciate the page count incrementing.

Overview of the Demo Application
We will first build a simple Java class 'Counter'. This class will be responsible for keeping count of pages viewed by the user. We will then build a Servlet which will use HttpSession.setAttribute() method to bind this Counter object to the user session. So every user will have a different session and thus every session will have a different Counter object attached to it.


 ( 2 Remaining ) Next

See all comments and questions (post-ad) posted for this tutorial.


Comments/Questions ( Threads: 3, Comments: 3 )
    Contains 1 or more replies by the Author of this Article.
    Contains 1 or more replies by Faisal Khan.

  1. outstreams redirected in java
  2. Sessions
  3. Session in JSP for Login & Logout

Post Comments/Questions

In order to post questions/comments, you must be logged-in. If you are not a member yet, then signup, otherwise login. Once you login then come back to this page and you'll see a form right here which will allow you to post comments/questions.

Please note, one of the benefits of signing up is to be notified immediately by email everytime you receive a reply to the thread you have subscribed to.

 
© 1999 - 2009 Stardeveloper.com, All Rights Reserved.