users@jersey.java.net

Re: [Jersey] Templates and Caching

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Tue, 19 Jan 2010 10:54:06 +0000

On Jan 18, 2010, at 4:52 PM, Max the Man wrote:

>
> Hi, I succesfully developed a @Provider for Velocity templates.
> However, I am not sure how to control caching headers for template
> results.
>
> My current solution does this:
>
> @Context
> HttpServletResponse res;
>
> public Viewable get(...) {
>
> ...
> this.res.setHeader("Cache-Control", "no-cache");
> return new Viewable("", this);
> }
>
> It works, but it is not very elegant.
> Is there a more natural way to do this?
>
> I notices that there is no way for cache control within the @Provider.
>

In your TemplateProcessor [*] inject HttpServletResponse.

Instead of injecting HttpServletResponse i recommend injecting
HttpContext if you want to override or check for existing Cache-
Control settings. For example:

   @Context HttpContext hc;

and in the writeTo method *before* any bytes are written to the output
stream do:

   if (!hc.getResponse().getHttpHeaders().containsKey("Cache-
Control")) {
     hc.getResponse().getHttpHeaders().putSingle("Cache-Control", "no-
cache");
   }

Paul.

[*] Note that this class is deprecated for the soon to be released
1.1.5 in preference of ViewProcessor, although TemplateProcessor
implementations will still work.