-
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:
1234567891011121314151617181920//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);
Close