YOUR FEEDBACK
Two great PDF creators
Michael Jahn wrote: related to the snapscan - are their an samples of the ...
SOA World Conference
Virtualization Conference
$50 Savings Expire May 23, 2008... – Register Today!


2007 West
GOLD SPONSORS:
Active Endpoints
Your SOA Needs BPEL for Orchestration
BEA
Virtualized SOA: Adaptive Infrastructure for Demanding Applications
Nexaweb
Overcoming Bandwidth Challenges with Nexaweb
TIBCO
What is Service Virtualization?
SILVER SPONSORS:
WSO2
Using Web Services Technologies and FOSS Solutions
Click For 2007 East
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
POWERBUILDER LINKS YOU MUST CLICK ON


Building JSP Applications with Jaguar CTS Part 5

Digg This!

What state am I in? Denial, confusion, Virginia...if you want your Web site to keep track of state between requests, you'll need to understand the Session API portion of the Java servlet and JSP specifications.

Where We Have Been
Before we dive into the Session API, let's review what we accomplished on the eMusic Web site in Part 4 (PBDJ, Vol. 9, issue 3). In that article we developed the Navigation.jsp page and the CheckLogon.jsp page to create the correct menu in our eMusic application (see Figure 1). I also explained the various uses of the include directive and include action to point out how to reuse code in a JSP application.

Where We Are Going
In Part 4, we saw that the checkLogon.jsp used by the Navigation.jsp page relied on session management to determine if a visitor to our Web site had logged in before it decided which menu to display. In Part 3 (Vol. 8, issue 12), we also described how the Logon.jsp page could keep track of the user name during an invalid logon attempt using session management. In Part 5 we look at how the Session API works and how you, as a developer, can take advantage of it.

Why We Need a Session API
The Web relies on the HyperText Transfer Protocol (HTTP), a stateless, object-oriented protocol used to transmit information between a Web browser (the client) and a Web server using a client/server model to issue requests and get a response. For additional information about HTTP, check out the World Wide Web Consortium at www.w3.org/protocols/.

HTTP's main drawback for developers is that it's stateless. Statelessness refers to the fact that the client is disconnected from the server after each request has been fulfilled. Because of this, there's no easy way to associate one request with another.

A typical HTTP request is illustrated in Figure 2 where a simple HTML page with an image is requested. It's initiated with a URL such as www.aegis.net. The browser connects to the Web server and starts downloading the HTML page and then the image embedded in it. Once all the files and resources associated with the HTML page are downloaded, the browser disconnects from the Web server. Should the client access another page on the Web site, the Web server will not be able to recognize that the client has already been there.

Web applications would not be very useful if there was no way to track and store information about clients as they navigate through our site. The JCP Expert Group that created the servlet and JSP specifications knew this and provided the Session API as part of the specification.

The Session API
We'll examine the Session API by looking at the login feature of the eMusic Web site. Because users who have logged into the Web site won't want to reenter their user ID and password for every request that requires validation, we'll need to store their user ID using the Session API. Since we're also storing the user ID during invalid login attempts, we'll need to store whether or not the user had successfully logged in as well.

The JSP specification provides several implicit objects. Using their predefined variable names, these objects are automatically available and ready to use. We've already talked about several, including the request and out objects. The session object is another implicit object made available to the JSP page.

The session object represents a user's session and is available to store information between requests. All requests made by the same user will access the same session object, so he or she will be able to get the information that was stored on a previous request. Information is stored in the session object using name-value pairs. The stored value is a java.lang.Object. Since this is the ancestor of every Java class, the session object can hold any Java class. Values are stored using the setAttribute method and accessed via the getAttribute method of the session object. Table 1 lists some of the common methods available on the session object.

The checkLogon.jsp page, which was included on the Navigation.jsp page, is shown in Listing 1. This page will be the first one typically encountered by users when they visit our site. The first thing it checks is whether or not the session object has been started using the isNew method. If the session is still considered new, we know the user has not logged in yet and no other processing needs to be done. However, if the session is not considered new, we need to check if the attribute "isValid" is equal to "OK". To do anything with data stored in the session object we must retrieve it. This is done using the getAttribute method:

isValidValue=(String) session.getAttribute("isValid");

The getAttribute method takes the name of the name-value pair used to store information in the session and returns the associated value. Note that the names used to store information in the session object are case-sensitive. In this case, the attribute is named "isValid" and would be added to the session object after a successful login on the validateLogon.jsp page (see Listing 2).

The Java object stored under the name "isValid" is a string. Notice in the listing that when we get the attribute from the session object, we need to cast it to the proper object type before we can use it. Once this is done, we can use the Java object any way we need to. We check for the value "OK".

When users access the site, they'll need to login eventually (if they want to add items to their shopping cart). This is done through the Logon.jsp page, where the following code is executed:

<%
String userID = "";
if (! session.isNew()) {
userID = (String) session.getAttribute("userID");
if (null == userID) userID = "";
}
%>

This code is similar to the code in checkLogon.jsp. It checks if the session is not new. If the session is still considered new, the user has not attempted to log into the Web site yet and the userID variable is defaulted to an empty string. Otherwise, it will use the value stored in the session object under the name "userID". By storing the user ID in the session, the page can keep track of the user who has logged in for future requests. It can also use the user ID during an invalid logon attempt and place it into the HTML form. The portion of the page that places the value of the userID variable in the HTML form is:

<TD align=left>
<INPUT TYPE=text SIZE=10 NAME="userID"
VALUE="<%= userID %>">
</TD>

Notice the Java variable userID, that was declared in a JSP scriptlet, is being written into the HTML output using a JSP expression.

Once a user has entered a user ID and password in the HTML form on the Logon.jsp page, he or she is directed to the validateLogon.jsp page. This page reads the "userID" from the request object and stores it in the session object.

String userID = request.getParameter("userID");
session.setAttribute("userID", userID);

The setAttribute method takes the name of the attribute that's being added and the Java object that represents the value. In our application this will establish the session, and isNew will no longer return true. It then checks to make sure that the user ID and password are equal. If they are, the "isValid" attribute is added to the session object with the value "OK". The user is then forwarded to the Home.htm page where the checkLogon.jsp page is rerun. This time the user will have been validated and the appropriate menu is shown.

Logging Off
In this article we want to add the capability to log off the Web site (see Figure 3). This enables users to leave their browser open with the knowledge that no one else can use the application with their user ID.

Since we're logging off, we can simply cancel the session using the invalidate method. This removes the current session object, making all the attributes associated with it eligible for garbage collection. Any subsequent calls to the isNew() method on the session object would return true after calling the invalidate() method. After removing the session we'll forward the user back to the Home.htm page. The following is the code for the Logoff_eMusic.jsp page:

<%@ page session="true" %>
<% session.invalidate(); %>
<jsp:forward page="Home.htm" />

Optionally, we could remove the "isValid" attribute from the session using the removeAttribute() method, so checkLogon.jsp will no longer recognize that the user is logged in.

<% session.removeAttribute("isValid"); %>

The difference here is that remove Attribute will remove only the name-value pair from the session. The session will still be valid and all other attributes will still be available to the user. Any subsequent calls to the isNew() method would return false. This technique is typically used when only certain attributes need to be removed. However, when logging off the application, it makes more sense to just remove the entire session.

How Long Will It Last?
There's no easy way to know when a user is finished with a Web site. We can provide a link to Logoff, but there's no guarantee that the user will click the link before moving to another Web site. To account for this, the session object is designed so that it will remain valid only until a specified timeout period has expired. The timeout period is the amount of time between two requests. If a user allows the specified amount of time to pass between requests, the container automatically invalidates the session. The default timeout period varies by container - EAServer is set up for 30 minutes. The timeout period can be specified using the setMaxInactiveInterval method of the session object or by using the <session-timeout> element in the web.xml file:

<web-app>
...
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>

For a J2EE application, using the web.xml file is the standard way to do this. Please note that the value set using the setMaxInactiveInterval method is defined in seconds while the value set using the web.xml file is defined in minutes. Passing the value of -1 will tell the container to never expire the session. However, the resources, particularly memory, on the Web server where a container is running are finite, so developers should never set the session timeout to -1.

How It Works
It's important to understand that not all the information placed in the session object is passed between the client and the container. The collection of name-value pairs is actually stored in memory on the server. The information is stored in a Java object that implements the HttpSession interface. The interface is located in the javax.servlet.http package. The servlet/JSP container vendor, in our case Sybase, is responsible for providing the implementation of this interface. How they choose to implement it is left up to them as long as it adheres to the HttpSession interface.

This object in memory is given a unique identifier called the JSESSIONID. It's the JSESSIONID that must be passed between the client and the server so the remaining state information can be associated with a request and retrieve. The container makes sure that the JSESSIONID is passed in on every request by placing the value in a cookie.

Let's look at how this works from the JSP container's point of view as we run through the eMusic site. When the user first hits the eMusic site, the checkLogon.jsp page (run from the Navigation.jsp page) determines that the session is new because it does not have a JSESSIONID (see Figure 4).

Later, when the user logs into the site through the Logon.jsp page, the userID and userPwd are passed into the validateLogon.jsp page. This page stores the user ID on the session object. This establishes our session between the client and the JSP container and a JSESSIONID is generated. The container generates the JSESSIONID. If the user ID and password are valid, it also stores this in the session object. Notice in Figure 5 that an HttpSession object is created in memory and bound to the JSESSIONID.

After successfully logging into the Web site the user is redirected to the Home.htm page where the checkLogon.jsp page is called again. This time it gets the JSESSIONID, which is passed in with each request in a cookie. The container uses the JSESSIONID to find the right session object in memory and associate it with the session object variable on the JSP page (see Figure 6).

Browsers can turn cookies off, which disables the Session API. To allow a Web application to use the Session API when cookies are turned off, the encodeURL method on the response object must be used for every URL in the site that the user can access. This adds the JSESSIONID to the URL so it's available for use by the JSP container.

The Page Directive
The session object is an implicit object that's available to every JSP page by default. However, using the page directive, a developer can turn off access to the session for a given JSP page. The following snippet shows the page directive:

<%@ page session="false" %>

When the session attribute of the page directive is set to false, the JSP page can no longer use the session object variable. By setting the session attribute of the page directive to false, the developer is avoiding the overhead of having the container set up access to the session object in memory; so it's recommended that every page that does not explicitly use the session object does this. This does not invalidate the current session in memory for the current user. After calling a JSP page that sets this attribute to false, subsequent requests to JSP pages in which the page directive sets the session attribute to true can access all the attributes in the session.

Session Scope
The session object and its values correspond to a single user. When several users log on to the eMusic site concurrently, each will get a session object in memory and a JSESSIONID, which uniquely identifies the session and ties the two together. A JSP page can't access the attributes in another user's session.

In addition, a session is only in scope in the Web application (ServletContext) in which it was created. Should our eMusic site have a link to another Web application, for example, the eBooks site, it won't be able to share information via the session object.

Changes to the Session API in Servlet 2.3 and JSP 1.2
This application was originally written using Jaguar CTS 3.6.1, which supports the Servlet 2.2 and JSP 1.1 specifications. Since then, the Servlet 2.3 and JSP 1.2 specifications have been finalized. I'll try to keep track of important changes between these specs and note them accordingly; however, there were no major changes to the Session API in the new specifications

Wrapping Up
Well, that wraps up this edition of JSP Corner. The code for the eMusic application is available on www.tamingjaguar.com. In the next edition we'll start to tackle the Search.jsp page and look at how to handle database access in our application.

About Mike Barlotta
Background Information: Michael Barlotta is the Director of Technology at AEGIS.net Inc (www.AEGIS.net). Mike is a Sun Certified Java Programmer and is recognized as an expert on the Sybase application server EAServer (Jaguar CTS), mentoring clients and speaking at conferences on the topic. He is the author of several books including Taming Jaguar and Jaguar Development with PowerBuilder 7 (both by Manning Publications). Be sure to check out Mike’s Web site www.TamingJaguar.com.

devimukesh wrote: It would be much more effective if there is an explnation of how to set the session time-out in web.xml from a jsp ,but not directly changing the value in xml file itself.
read & respond »
PBDJ LATEST STORIES . . .
3rd International Virtualization Conference & Expo: Themes & Topics
From Application Virtualization to Xen, a round-up of the virtualization themes & topics being discussed in NYC June 23-24, 2008 by the world-class speaker faculty at the 3rd International Virtualization Conference & Expo being held by SYS-CON Events in The Roosevelt Hotel, in midtown
The PB Future: More on Graphs in PowerBuilder 11.5
Last week I posted a screen shot of the new 3D Rendering capabilities being added to some of the 3D graphs in PowerBuilder 11.5. It was met with mixed reviews on the PowerBuilder Futures newsgroup (forums.sybase.com) so I went back to the drawing board to see what I could come up with.
BluePhoenix Expands Modernization Collaboration with Microsoft
BluePhoenix announced that it has expanded its collaboration with Microsoft on legacy modernization projects. The collaboration provides customers moving their applications or databases to .NET-based environments the best in both modernization services and technical support. BluePhoeni
Sybase PowerBuilder Delivers AJAX and .NET Enhancements Enabling Rich Internet Application Development
Sybase announced that AJAX development capabilities and further Microsoft .NET enhancements have been added to the latest version of Sybase PowerBuilder 11, the premier 4GL rapid application development (RAD) tool. PowerBuilder 11.2 represents another milestone in the PowerBuilder road
PowerBuilder 11.2 Released: Sybase's Flagship IDE
Sybase has released the production version of its flagship .NET development tool - PowerBuilder version 11.2. This latest release of its premier IDE for RAD includes not only standard fixes but also a good list of new features. Here is the 'Coles Notes' version of these new features.
PowerBuilder Takes You To .NET
In June of 2007, Sybase released PowerBuilder 11. PowerBuilder developers can now deploy PowerBuilder components as .NET Assemblies or as .NET Web Services. A PowerBuilder developer can now create these .NET resources so that those who develop .NET solutions can benefit from PowerBuild
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE
BREAKING POWERBUILDER / SYBASE NEWS
Sybase and Sun Set Guinness World Record for World's Largest Data Warehouse
Sybase, Inc. (NYSE:SY), the largest enterprise software and services company exclusively