开发者

HTTP CacheControl with Jersey and json implementation

开发者 https://www.devze.com 2023-02-06 14:53 出处:网络
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:

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("jsontest开发者_如何学JAVAcache")
@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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消