RESTful设置Pragma和Expires

时间:2013-12-03 15:52:38

标签: java rest caching jersey jax-rs

如何使用RESTful服务设置"Pragma" = "no-cache""Expires" = "0"

我添加了以下内容

 CacheControl cc = new CacheControl();
 cc.setNoCache(true);
 cc.setNoStore(true);
 cc.setMustRevalidate(true);
 cc.setMaxAge(0);

以上返回以下标题

HTTP/1.1 200 OK
Cache-Control: no-cache, no-store, no-transform, must-revalidate, max-age=0
Content-Type: application/json
Transfer-Encoding: chunked

不确定如何设置"Pragma" = "no-cache""Expires" = "0"

任何帮助都非常值得赞赏。

1 个答案:

答案 0 :(得分:1)

您可以通过注入HttpServletResponse或返回Response对象,在Jersey中设置您喜欢的任意响应标头。

HttpServletResponse示例:

@Produces(MediaType.APPLICATION_JSON)
public MyObject getValues(@Context HttpServletResponse response) {
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "0");
    ...
}

响应示例:

@Produces(MediaType.APPLICATION_JSON)
public Response getValues() {
        return Response.status(200)
                 .entity(new MyObject())
                 .expires(new Date())
                 .header("Pragma", "no-cache")
                 .type(MediaType.APPLICATION_JSON);
}