Sun Java System Web Server 7.0 Update 2 Developer's Guide to Java Web Applications

cache Tag

The cache tag enables you to cache fragments of your JSP pages. It caches the body between the beginning and ending tags according to the attributes specified. The first time the tag is encountered, the body content is executed and cached. Each subsequent time is run, the cached content is checked to see whether it needs to be refreshed. If so, it is executed again, and the cached data is refreshed. Otherwise, the cached data is served.


The following table describes attributes for the cache tag.

Table 5–3 cache Attributes






(Optional) The name used by the container to access the cached entry. The cache key is added to the servlet path to generate a key to access the cached entry. If no key is specified, a number is generated according to the position of the tag in the page. 



(Optional) The time in seconds after which the body of the tag is executed and the cache is refreshed. By default, this value is interpreted in seconds. To specify a different unit of time, add a suffix to the timeout value as follows: s for seconds, m for minutes, h for hours, and d for days. For example, 2h specifies two hours.



(Optional) If set to true, the body content is executed and served as if no cache tag is active. This offers a way to programmatically decide whether the cached response should be sent or whether the body must be executed, even if the response is not cached.



(Optional) If set to true, the body content is executed and the response is cached again. This setting enables you to lets you programmatically refresh the cache immediately, regardless of the timeout setting.



Specifies the scope of the cache. Valid values are request, session, and application.


The following example represents a cached JSP page.

<%@ taglib prefix="mypfx" uri="/com/sun/web/taglibs/cache" %>
   		String cacheKey = null;
    		if (session != null)
      	cacheKey = (String)session.getAttribute("loginId");
   		// check for nocache
			   boolean noCache = false;
   		String nc = request.getParameter("nocache");
   		if (nc != null)
      	noCache = "true";
			   // force reload
			   boolean reload=false;
			   String refresh = request.getParameter("refresh");
			   if (refresh != null)
     		reload = true;
			 <mypfx:cache key="<%= cacheKey %/>" nocache="<%= noCache %/>" 
       refresh="<%= reload %/>" timeout="10m"/>
		  	   String page = request.getParameter("page");
   		if (page.equals("frontPage") {
       	// get headlines from database
		    } else {
							<mypfx:cache timeout="1h"/>
				<h2> Local News </h2>
			   // get the headline news and cache them