JSPs are able to run complex Java code within tag libraries, making JSP files easier to maintain and more useable by nondevelopers. While many tag libraries are available both commercially and as open source projects, most simply duplicate what could otherwise be written with a small Java scriptlet. Few have found innovative ways to use custom tags that were not readily possible before custom JSP tags existed.
The OSCache tag library, created by the OpenSymphony project, breaks new ground by providing fast in-memory caching within your existing JSPs. While some vendors support various forms of caching, those solutions are vendor specific. OSCache will run on any JSP 1.1-compliant server, and can cache your existing JSP code blocks either for all users or on a per user basis. It also has advanced features for added flexibility, including caching to disk, programmatic flushing of caches, and exception handling. And, as with every venture of the OpenSymphony project, the OSCache code is released freely under an open source license.
In this article, I will walk you through the design of a fictitious auction Website to show how the OSCache tag library works. The fictitious Website will include an administrative page that reports on recent activity, a rich homepage with various types of promotion information, and a special navigation bar that includes each user's open auction activity.
Part of the auction Website includes a real-time administrative report that takes the database server several seconds of CPU time to create. This is important as we can potentially have several managers who want to monitor the system, and we want to avoid rerunning this report. To do this, we will wrap the entire page in an application-scope cache tag that refreshes every hour. Some vendors have comparable features, but this OSCache feature is only the tip of the iceberg.
To keep the examples simple, we won't worry too much about formatting, but do realize that the cache tags could be interspersed with as much HTML as needed. We'll start the page by adding the tag library declaration:
<%@ taglib uri="cachetags" prefix="cache" %>
We'll now wrap the cache around the entire page. This will be the first use of the OSCache tag library. As the cache tag wraps regular JSP code, you can finish debugging your code before enabling the cache. The cache tag defaults to one hour.
<cache:cache> .... complex administrative report .... </cache:cache>
The administrative page is now cached, so if a manager visits the same report within an hour from the time the report was generated, it will see a cached result and the database server will be untouched.