如何在Play框架中为网址设置Etag?

时间:2015-05-15 12:47:11

标签: http-headers playframework-2.0 http-etag

我已经搜索过在playframework中设置Etag。我得到的只是 1)https://www.playframework.com/documentation/2.0/Assets
2)https://www.playframework.com/documentation/2.0/JavaResponse

第一个选项仅适用于资产或文件。 第二个选项不起作用。我刚刚添加了示例中给出的三个。

1 个答案:

答案 0 :(得分:4)

实际上,在Play的doc for assets(您首先关联的)和Wikipedia Typical usage section中都会使用Etag。

在操作开始时,您需要确定自上一代Etag以来所请求的资源是否已更改,如果是,则需要使用新Etag生成新内容,否则您只返回304 NotModified响应。

当然一切都取决于所请求资源的类型,无论如何,非常干净的样本可能是一个数据库实体,其中一些ID和字段包含上次修改的日期/时间:

public static Result eTaggedFoo(Long id) {

    Foo foo = Foo.find.byId(id);
    if (foo == null) return notFound("Given Foo was not found");

    String eTag = DigestUtils.md5Hex(foo.id + foo.lastModification.toString());

    String ifNoneMatch = request().getHeader("If-None-Match");
    if (ifNoneMatch != null && ifNoneMatch.equals(eTag)) return status(304);

    response().setHeader(ETAG, eTag);
    return ok("Here you can see the " + foo.name + ", last modified: " + foo.lastModification.toString());

}