Controlling the cache headers for a RESTlet directory
My previous post described how to serve webjars with RESTlet. This post will describe how to add caching so that users don’t swamp your servers with requests. Put simply, you put a filter in the chain before the directory and modify the HTTP headers of successful requests. Like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
//add a webjars listener. final Directory dir = new Directory(getContext(), "clap://class/META-INF/resources/webjars"); //add cache headers to the webjars so we're not swamped by requests, set things to expire in a year. Filter cache = new Filter(getContext(),dir){ protected void afterHandle(Request request, Response response) { super.afterHandle(request, response); if (response!= null && response.getEntity() != null) { if (response.getStatus().equals(Status.SUCCESS_OK)){ final Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, 1); response.getEntity().setExpirationDate(calendar.getTime()); response.setCacheDirectives(new ArrayList<CacheDirective>()); response.getCacheDirectives().add(CacheDirective.maxAge(31536000)); } } } }; this.attach("/webjars", cache); |