|
Comments
Did you read today's front page stories & breaking news?
SYS-CON.TV
|
General Java Servlet Session Display
Servlet Session Display
By: Peter Kobak
Feb. 1, 2000 12:00 AM
With the release of the Java 2 Platform, Enterprise Edition, Java-based Web application servers are gaining in popularity. Although application servers have been around for a few years, they forced programmers to be tied to a proprietary API. Support of J2EE by application server vendors standardizes the API we write to, easing training, staffing and support costs. Perhaps most important in our dynamic Web vendor environment, writing code to an industry standard reduces the huge risk a customer takes in choosing a particular vendor should that vendor disappear. In this article I'll explain the basics of Java servlet sessions and why careful monitoring of your sessions will be important in a large site using multiple application servers. Then I'll present a simple utility to check your servlet sessions.
Application Servers
Unless it was designed with saintlike attention to isolation and modularity, a page change, database change or business logic change ripples through all parts of the application. More important, as traffic goes up, more and more code must be dedicated to resource management: database connection management to keep the database from getting swamped, thread or process control to keep the Web server from thrashing, and load distribution to handle volume. Sound scary? Ask anyone who's had to maintain an older site for a few years using only a C compiler. Application servers help reduce the housekeeping and management burdens, allowing developers to concentrate on the application itself. On the presentation layer a page layout mechanism enables the use of templates to insert data in dynamic pages. A transaction monitor allows you to manage the sequence of transactions, roll back across heterogeneous databases, use a connection pool and access a common API to address different databases. Business logic modularity is supported through formal mechanisms. Automatic caching is available for database resultsets and HTML pages. Across it all are management functions to perform load balancing and distribution among threads, to make full use of available processors and to allow for graceful degradation under stress. The most serious application servers also support load balancing or failover between servers. Java-based application servers perform these functions using a standard set of APIs (see Figure 2). Instead of learning the quirks of your vendor's API, you can rely on information from multiple sources and have access to many resources - books, sites and newsgroups - not to mention the fine magazine you're reading now. You also avoid the sometimes deadly vendor lock. Using a proprietary system is like locking yourself in a jail cell; a standards-based system is similar, but you get to smuggle in a hacksaw. Although four layers are shown in the application server in Figure 2, there's nothing stopping you from skipping layers or using a more complex pathway. For instance, you may find that for all their sophistication EJBs are overkill. You may choose to go directly from a servlet to a JDBC call. However, to get business-layer isolation you'll probably want to use a bean separate from servlet code. Also, it's not uncommon to have a chain of servlets to provide layered user data validation and transaction control.
Presentation Layer
JSPs allow you to mix servlet code with HTML, which gives you a nice layout of static HTML with the dynamic bits placed as Java code. JSP source is compiled into an HTML file and a Java file, but the application server does it for you. Some servers even recompile on the fly, recognizing a change to JSP source and doing all the compiling and class reloading automatically (pretty slick). JSPs can do most things a servlet can, and in addition support JavaBeans. You probably know about beans, but for the purpose of JSPs, the only important rule to follow is the coding pattern of using getProperty() and setProperty() methods - where "Property" is a bean property name that's usually just a field of the bean class. Since arbitrary Java code can be executed in a JSP, a bean can be used just by invoking it as a class in the usual way. Beyond this, though, there's support for beans. You can create and use a bean for a period that extends beyond the life of the current request (see Table 1). There's also a JSP syntax to set and get bean properties, although standard Java syntax works just as well. Typically, the beans invoked from a JSP contain your business logic, and directly or indirectly invoke back-end systems and databases. Even if your logic is simple, you're better off minimizing the amount of Java in a JSP. Think of a JSP's Java code as performing just enough logic to invoke business beans. The beans do their work, then the JSP extracts bean properties to put data on the HTML page.
Sessions
You can store an object in a session by invoking a method of HttpSession and giving the object a name. On the same or subsequent requests, invoking a get method with the object's name can retrieve the object. A servlet accesses the HttpSession directly. A JSP can also use the session directly but, as you probably guessed, a bean stored with a "session" lifetime is stored into and retrieved from the HttpSession for you.
Distributing Servlet Sessions
Distributing fine-grained work between servers is even more clever. However, if your application is supposed to work with a consistent HttpSession, the session must be maintained on multiple servers (see Figure 4). Application servers can have more than one policy for sharing sessions, but it's clear that if you need to have robust transactions (that is, user transactions that can survive if a server goes down) your HttpSessions must somehow be distributed to the peer server(s). Although it's technically possible for a server to implement distributed sessions without using serialization, the serialization mechanism native to Java is the obvious and simplest way for a server to distribute the data from the objects living in the session. Even though the app server does the hard work of enforcing session distribution policies, you have to make sure all the objects you store into HttpSession are serializable.
Serializing Session Objects
Serialization is at the core of several Java standards involving the movement or storage of the object state outside of system memory. It's a powerful mechanism but simple to use. An object that implements the java.io.Serializable interface can have its state, and the state of all constituent objects, written to a java.io.ObjectOutputStream. The object can then be reconstituted by reading the same stream from an ObjectInputStream. To allow an object to be serialized, a programmer need only specify "implements Serializable" and be sure all constituent objects are serializable (or primitive) as well. Notably, a programmer doesn't need to code any methods at all to support serialization. Just about any JDK class you'd sensibly want to serialize already implements serialization. Although it's easy to mark an object as serializable, the subtle danger is that it's easy to forget to mark an object deep in a hierarchy. You'd learn about the oversight only at runtime when ObjectOutputStream throws a NotSerializableException, and then only if you're vigilant. The size of a serial stream can be difficult to predict for the same reason: it's often not surprising to find that a field of your object was set to an object pointing to a large tree of objects. During serialization, you may find that the tree-following serialization process dutifully saves a lot of data you don't actually need.
Session Monitor
The JSP "SessionTester.jsp" is in Listing 1 and the worker bean "SessionTesterBean.java" is in Listing 2. In the JSP you can see how easily Java and HTML are mixed. Note that "<%" ... "%>" surrounds Java statements, while "<%=" ... "%>" surrounds a Java expression that's converted to a string and inserted in the surrounding HTML. (I have to comment how wonderful it was to start using JSP after building cgi-bins for years in C. It was like emerging from a programmer's gulag.) It's a stretch to call the SessionTesterBean class a bean. But the term bean is an accurate way to differentiate an independent Java class in an app server from a servlet or JSP. Plus, it sounds better than "Java worker class." The SessionTesterBean consists of a few static methods, one of which is called from the JSP. Each value in the session is found, then dumped by writing HTML to the "out" stream. Note the direct way I find the serialized size of each session value object - I just write the object to an ObjectOutputStream and find the number of bytes. I also check for exceptions and report them, which helps find any nonserializable object in your object tree. Installing the utility can be different for every server vendor. Compile the .java file with the compiler in your app server's JDK. If necessary, "compile" the .jsp file, although many app servers automatically recognize, compile and install new JSPs. You have to put the .jsp file in a location that allows the app server to invoke it with a URL, and you have to put the .class file in a package directory, SessionTesterBeans, along the CLASSPATH that's active when the JSP is active. This may involve configuration efforts in your app server, but if you've already done some playing with JSPs and beans, you probably already know where to install the files in an existing configuration. To use the utility, establish some HttpSession data in your own servlet or JSP, then simply use the URL needed to invoke SessionTester.jsp. The page returned shows a summary of the objects in the current session along with their sizes. Pressing a button displays session parameters and the composition of each object within it. Reader Feedback: Page 1 of 1
Latest Cloud Developer Stories
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
|
SYS-CON Featured Whitepapers
Most Read This Week
Breaking Cloud Computing News
|
|||||||||||||||||||||||||||||||||||||||||||||||||