Servlet Caching Sample

I wanted to try how to enable caching for Servlet and JSP so i tried creating a simple DynaCacheSample Web application. This application has a DynaCacheServlet, that forwards control to dynachache.jsp for actual markup generation. So i wanted to see how can i enable the Servlet Side cache.

I created this cachespec.xml file in the WEB-INF folder of my web application

<?xml version="1.0" ?>
<!DOCTYPE cache SYSTEM "cachespec.dtd">

<cache>
<cache-entry>
<class>servlet</class>
<name>/dynacacheservlet</name>
<cache-id>
<component id="action" type="parameter">
<required>false</required>
</component>
<timeout>180</timeout>
</cache-id>
</cache-entry>
<cache-entry>
<class>servlet</class>
<name>/dynachache.jsp</name>
<cache-id>
<component id="action" type="parameter">
<required>false</required>
</component>
<timeout>180</timeout>
</cache-id>
</cache-entry>
</cache>


As you can see that i have two cach-entry element one for the /dynacacheservlet URL, that specifies that cache content of the /dynacacheservlet URL and other for /dynacache.jsp that caches content of the dynacache.jsp.

Now other part of the question is what should be the cache key, i.e. if you have a news site that generates same content for same URL for all the users you can say that cache content based on URL but if you have a site which has view mode and update mode you can say that cache content only when value of action request parameter is view,.. THe component elements let you configure the key. You can also create your own class that will get control to generate cache key based on the request. Take a look at cachespec.xml for more information

You can download the DynaCacheSample.war from here

Once my DynaCacheSample.war was deployed i tried hitting DynaCacheServlet by going to http://localhost:9080/dynasample/dynacacheservlet and this is what i see in the CacheMonitor application



As you can my request to /dynacacheservlet is cached as well as the JSP page that DynaCaheServlet is including to generate response is also cached.

No comments: