Thursday, March 24, 2011

Chapter 20: Introduction to Session Management

In one of the previous chapters, we saw what a Session is, what its purpose is and how it is used. In fact, one of our readers even posted a comment stating that the description was very simple and did not cover the full length and breadth of Session Management. Well my friends, that was just the introduction and in the next few chapters, I will probably bore you to death with the details of Session Management.

So, lets get started!!!

Why do we need a Session?

When one page needs to share information with another, the scope of the data broadens beyond processing a single request. This is because, when a response gets committed, all the data that was held in the request that generated that response is destroyed. So, if you want that data in another page, you will be looking at a blank request object with no data in it. When such a need arises, you must send the data from one page to the server and from the server to the next requested page, whether it be the same page or another page altogether. There are several ways to share state information between requests. However, the primary or the easiest way is to use sessions.

How Do Sessions Work?

The container generates a session ID. When you create a session, the server saves the session ID on the client's machine as a cookie. If cookies are turned off then it appends the ID in the URL. On the server, whatever you add to the session object gets placed in server memory—very resource intensive. The server associates that object in memory with the session ID. When the user sends a new request, the session ID is sent too. The server can then match the objects in its memory with that session ID. This is how we maintain client state.

What are Cookies?

In the previous paragraph about how sessions work, we used the term cookies. A cookie is a tiny text file that is maintained by the browser to do things like store unique IDs. They are normally small (~1KB) and saved in the OS cookie directory or folder. There are numerous browsers that handle cookies in various ways. You can go to c:\documents and settings\your login and search for cookies folder and try seeing what kind of files are placed in it by your browser.

In the old days they were used for all sorts of things, including storing personal data like passwords. The popularity of doing so has waned. Today, especially with servlets, it is better to store most information in sessions than cookies. But it is still important to understand cookies before discussing sessions.

As you can see in the image above, there are many cookies on my machine. Those shown are only a few that have been created on my Windows 7 Sony VAIO Laptop. Originally, folks put actual data like names and addresses in cookies because there wasn't anywhere else to save these valuable pieces of data. Today, the information in a cookie is primarily an identifier of sorts.

Vendors implement session IDs differently. Let us dig into Tomcat to see how it handles sessions IDs. The following snippet, edited for clarity, is how a session ID is generated:

/**
* Generate and return a new session identifier.
*/
protected synchronized String generateSessionId() {

// Generate a byte array containing a session ID
Random random = getRandom();
//int SESSION_ID_SIZE= 16;
byte bytes[] = new byte[SESSION_ID_SIZE];
getRandom().nextBytes(bytes);
bytes = getDigest().digest(bytes);

// The remainder of routine converts
// the byte array to a String of hexadecimal digits.

// This returns something like:
// 62A027E37975F305B07555859780E423
// see Listing 6.6
return (result.toString());
}

Web sites keep track of your activities (such as a shopping cart) with a standard session ID, which assigns each visitor a unique, random number. The servlet specification doesn't address how browsers are supposed to store the session ID. Some browsers store it in memory (but send/receive in request/response header as a cookie), while most store it in a cookie file. For example, when I recently visited Amazon, its servers sent my browser a new session ID which was stored in a cookie file called administrator@amazon[1].txt. In this cookie was the following session ID, among other things like date timestamp:

session-id
002-0150365-1700034
amazon.com/

Cookies have been the target of privacy advocates since the beginning of the internet. Cookies are now used for many things, including the suspicious tracking of your activities as you surf the Internet. Some people call the use of cookies to track activity Web bugs. Some companies are paid to monitor you as much as possible to create a profile. And since that is not in the scope of the exam, we arent going to bother much about them.

Most of the cookies on our machines are not used for anything sinister. You can thwart all this by turning off cookies and images. You can do this in IE by going to View -> Internet Options -> Advanced -> selecting Prompt before accepting Cookies, and clicking OK.

In fact, cookies are used for good far more often than bad. For example, when I go to Amazon.com, I get a familiar view because they remember what I did on my last visit. Amazon can do that because it placed a file on my machine called administrator@amazon[1].txt (the browser actually does this) containing this:

session-id
432-5447995-1125358
amazon.com/
0
4322765824
89901156
321345632
79444758
*
session-id-time
8731881600
amazon.com/
0
9985765824
44191156
185745632
09789758
*
ubid-main
0883061-5210078
amazon.com/
0
6796341376
69581269
777869456
29476039
*
x-main
3xBkjhwcqmPgTz7hgffU8UoFvMDSWX
amazon.com/
0
7896341376
1969969
939053232
9770408
*

I like the idea of Amazon tracking my activities. They are open about it and I can stop them any time I wish. But, it becomes problematic when companies do it stealthily or use it to trouble you. In this case Amazon is a genuine website and I seriously have 0 problems with them saving a cookie in my laptop. Afterall, it is going to help me the next time I visit their site so I practically have no issues with it.

The following are the four most frequently used methods for persisting data between views:
• Field-field: Value of a field in a request is copied to value of same field in response.
• Hidden form field: Data is placed in the HTML in a hidden form field.
• Query string: Some data is appended to the query string or a hyperlink in the HTML.
• Cookie: A small text file created by the browser that stores data sent by the server.

These four approaches are the ones most often used; however, session technology does more for you. The following section describes how Java uses sessions to help you maintain client state.

Using Session Objects

The HttpSession object is very powerful and has many features. Before we dig deep into the world of Sessions, let us take a look at the important methods they have so that we can use them effectively.

getAttribute(java.lang.String name) - Returns an Object associated with that name that was stored in the session object.
getAttributeNames() - Returns an Enumeration object that lists the names of the objects stored in the session object.
getCreationTime() - Returns a long containing the date stamp of creation.
getId() - Returns the id of the session as a String representing the unique identifier assigned to this session.
getLastAccessedTime() - Returns a long containing the date stamp of the last time the session was accessed.
getMaxInactiveInterval() - Returns an integer representing the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.
invalidate() - This destroys a session. It can't be referenced after this method has been called.
isNew() - This tells you whether the client knows about the session. In other words, the has session been created by the server, but the client hasn't acknowledged receiving the session ID yet.
removeAttribute(java.lang.String name) - This removes an attribute. It deletes it from the session object.
setAttribute(java.lang.String name, java.lang.Object value) - You use this method to add objects to a session.
setMaxInactiveInterval(int interval) - Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.
getValue(java.lang.String name) - Returns an Object associated with that name that was stored in the session object. As of Version 2.2, this method is replaced by getAttribute(). The getAttribute() method will be on the exam, not this one, but it is here for completeness.
getValueNames() - Returns a String array with a list of names associated with the objects added to a given session. As of Version 2.2, this method is replaced by getAttributeNames(). The getAttributeNames() method will be on the exam, not this one, but it is here for completeness.
putValue(java.lang.String name, java.lang.Object value) - You use this method to add objects to a session. This has been deprecated. As of Version 2.2, this method is replaced by setAttribute(java.lang.String, java.lang.Object). The setAttribute() method will be on the exam, not this one, but it is here for completeness.
removeValue(java.lang.String name) - This removes a value, but retains an attribute name in the session. The name is valid but the object is null. This has been deprecated. As of Version 2.2, this method is replaced by removeAttribute(). The removeAttribute() method will be on the exam, not this one, but it is here for completeness.

The preceding methods are the ones that will appear on the exam. For the moment, just relax and don't worry about how and when to use these methods. That is exactly what I am going to explain in the subsequent chapters.

Previous Chapter: Self Test - Chapters 6 to 19

Next Chapter: Chapter 21 - Storing & Retrieving Session Objects

No comments:

Post a Comment

© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers