Search code examples
restscalajerseycache-control

HTTP CacheControl with Jersey and json implementation


I want to add the CacheControl intormation to a GET service that use the json binding. I found that to add the cacheControl to a response the REST service sound like this:

@GET
@Path("cacheheadertest")
@Produces({"*/*"})
def testcache():javax.ws.rs.core.Response {
    val rb:Response.ResponseBuilder = javax.ws.rs.core.Response.ok("chached test message")
    val cc = new CacheControl()
    cc.setMaxAge(60)
    cc.setNoCache(false)
    rb.cacheControl(cc).build()

}

but I have a REST service that produce json messages and the jersey library transform automaticcally the java object from java to xml/json.

@GET
@Path("jsontestcache")
@Produces(Array(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML))
def myjsontestservice(@HeaderParam("X-TOKENID") tokenId: String,
@QueryParam("clientId") clientId: String):com.test.MyResultClass = {
 val response= new com.test.MyResultClass
 [...]

 response
}

How can I add the cache control to the response of myjsontestservice service? Do I need to use a filter and append the cachecontrol once the response has been created by jersey? thanks million Flavio


Solution

  • You would still need to return a Response object.

    def somejson() : Response = {
      val builder = Response.ok(new com.test.MyResultClass);
      val cc = new CacheControl()
      cc.setMaxAge(60)
      cc.setNoCache(false)
      builder.cacheControl(cc).build()
    }
    

    Jersey's interceptors will automatically convert your class into a JSON object.