Atom Conditional GET in Servlet
I’m using ROME to write an Atom/RSS newsreader client. ROME has this neat little interface called FeedFetcherCache that works with HttpURLFeedFetcher to support “conditional GETs”. This means the ROME client will first send an HTTP request with the “If-Modified-Since” header. If the server replies with HTTP 304 Not Modified, Rome knows not to bother fetching the entire feed. This can significantly reduce load on servers that generate dynamic feeds.

For this to work, your server-side code needs to properly handle this kind of request. If your feed is a static file delivered via Apache or comes from some blogging tool, it probably already works.
But in my case, I am generating an Atom feed dynamically using a servlet. My servlet ignored the If-Modified-Since header, so every request resulted in the whole feed being generated from the database.
How I Fixed It
First, I Googled and found this wonderful explanation of HTTP conditional GET by Charles Miller. The fix is very easy, requiring two changes to the servlet. First, I populate the Last-Modified header in my doGet(...) method.
Note that I also generate the entire feed in the doGet(...) method. ROME needs to download the feed the first time, then it caches this Last-Modified date in its FeedFetcherCache. Here is the important part of the code from my servlet:
protected void doGet(...) {
Date feedModifiedDate = ...;
servletResponse.setDateHeader("Last-Modified", feedModifiedDate.getTime());
... generate the feed
}
This handles the normal HTTP GET. But how does the servlet know how to process a request containing the If-Modified-Since header? It turns out this is built-in to the servlet API, you simply need to override the getLastModified(...) method in your servlet:
protected long getLastModified(HttpServletRequest req) {
Date d = ...compute the modified date for the feed
return (d == null) ? -1L : d.getTime();
}
And that’s it. Now my Atom newsreader client only downloads the entire feed when the date actually changes.
Not Just for Atom
Clever It’s Just a Bunch of Stuff That Happens readers will recognize this technique works for all kinds of servlets, not just Atom-producing servlets. Whenever you can determine a modification date, you should always strive to:
- Set the
Last-ModifiedHTTP header on the servlet response - ALSO override the
getLastModified(...)method
These work together, along with intelligent HTTP clients, to reduce network traffic and server load.