clicking on this will visually collapse the text block directly below it

Java Servlet Tutorial Part 6 - The Session Object, September 2002

Well now, we've gotten going building our servlets, throwing a few neat things out to the browser but all in all we aren't do much except creating HTML on the fly, not that there's anything wrong with that but there has to be more! So let's start diving into some fun stuff that we can really WOW them with. I've picked sessions for our next topic in this ongoing saga because of all the things (next to JDBC) we can use in Java, sessions are one of the most useful to any web developer.......so let's dive in and get our hands REAL DIRTY!

  First thing we have to realize is that the HttpSession is an interface NOT a class! What's that mean? Well first of all you don't create a session like this:

HttpSession mySession = new HttpSession();

Nope, Nope, Nope that won't do at all. A session object is declared and created via a line of code such as this: HttpSession mySes = req.getSession(boolean create); The getSession method of the HttpServletRequest object returns the current session, if one exists. There are two methods for this, one without any parameters & one with a boolean. The no param version will ALWAYS create a session if the request object doesn't return one. I much prefer the boolean param version for 99% of my servlet work (Control Freak, ya know.) If true is passed to the method and no current session exists a new session will be created, likewise if false is passed no session will be created. This has some very interesting possibilities that we will delve into later. So let's add some session handling to our servlet to start our adventure in sessionland! Click Here and check the first line of code in the doPost. OH, Please note one other change in the code from this point. You know how we always do object() name = new object()? Well, if you are only using the object one time you DON'T need that nonsense. Look at this re-do of the previous code & see how the object that are used one time are treated ... once again this is a TINY bit advanced but I think you'll see the point. Click Here to see the new code!

The first thing you have to know about Sessions, you MUST get your session object BEFORE doing ANY response work. I can't stress this enough. Don't get a writer, set the content type....nothing before getting the session. I purposely code it the first thing in my servlets just to avoid any problems. This is the source of many, many problems with beginning servlet programmers and can cause session objects to act VERY strange so avoid the headaches now & just get used to doing it this way. One other side bar before we get going here is that Java sessions will NOT work if your users have non-persistent (not written to the user's hard drive) cookies disabled! Strange but true. You see a Java session sends information back to the user's browser that most browsers will construe as a cookie. We will get to how to get around this later in this tutorial. Anyway, we are now creating a session if none exists when the form is submitted so let's add this information to the users session like this. You will also notice I have had to wrap the primitives in their correct object wrappers to add them to the session. So, believe it or not that's all there is too it, more or less. Let's send our info from the form to our new servlet Click Here, submit the form & then click on the button to go to the next page. Bingo, all our information is there! Let's take a look at the code that retrieves this information from the session object. Here is our SessionTest servlet that grabs all of our info.

I'm not going to waste time formatting this page because I want you to focus on the session work itself. Note, once again we are getting the session first thing in our doPost but this time we are passing false because we know anyone coming into this servlet SHOULD have a session (We will get back to this in a moment) so we don't want to create one.

One very important concept to know about sessions is that they are basically a type of HashTable. You put things into a session object with a key value pair just like a HashTable and you retrieve them in the same fashion, using the unique key you put that particular object in with. For this reason you must remember that you you will destroy a currently held object in a session if you try to add another with the same key, of course this can also work in your favor if you wish to keep updating information in a user's session. Also note we are casting all of our incoming variables back into their correct type before we assign them to our variables. This is the same whether you are using standard variables or your own objects. If you had a Customer object that you put into the session you would simply do this to retrieve it:

Customer myCust = (Customer)ses.getAttribute("customer");

Then you can simply call your set & get methods from your new myCust object and all of your info will be there! Just that simple, just that quick. This brings up a question I get a lot.....What can you put into a session? Literally anything you can think of, that's why sessions are so cool. I have seen people take 10,000 row JDBC result sets and stuff them in a session object. Now I don't recommend you get this crazy but sessions really open up a TON of possibilities that other forms of user tracking just don't offer.

There are just a couple of more things you really need to know about sessions before we venture on. The first is how long a session lasts before it will "die". Most containers I've used (Resin, Tomcat & JServ) have a standard "life" of 20 minutes. Most of these servlet engines also have a way to set this time to anything you want but you also have the means to do it right in your code with the setMaxInterval(int interval) method. Next you will need to destroy sessions yourself (IE: when someone logs out of a site) to do this you can use the invalidate() method. There are other methods but these really are the important ones when learning to use sessions.

Customer Comments

clicking on this will visually collapse the text block directly below it
I won't go anywhere else. They have gained my trust & confidence and have a great reputation in my book!
Lissa Lee, bathandbodycare.com | More Testimonials >>

Latest Articles / Tutorials

clicking on this will visually collapse the text block directly below it |
Our RSS Article Feed Available as RSS Feed!

Check here often for articles & tutorials that will help make your business grow!

| More Articles & Tutorials >>

Partner Comp. & Friends

clicking on this will visually collapse the text block directly below it