How to Use HttpServlet.getLastModified to Improve Client-Side Caching
HTTP clients often use a local cache to avoid requesting the same files again and again. To validate that the cache is not outdated and update the cache with a single request, the client can send a conditional GET: the If-Modified-Since header attribute tells the server to send the document only if it has been modified since the value given in If-Modified-Since. Otherwise the server responds with the status code 304 (Not Modified).
It's easy to implement If-Modified-Since with the Servlet API: just override the method getLastModified to return the last modification date of the requested document, and the container will transparently take care of conditional GETs for you:
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
// Servlets that shows the current date
public class DateServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
writer.print("<html><head><title>Time</title></head><body>");
writer.printf("The current date is: %tF", new Date()); // '%tF': format as yyyy-mm-dd
writer.print("</body></html>");
}
protected long getLastModified(HttpServletRequest request) {
// the date changes every day at midnight!
GregorianCalendar cal = new GregorianCalendar(); // current time
cal.set(Calendar.HOUR, 0); // set to midnight
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis(); // convert to ms since 1970
}
}

