播放框架2.1 HTTP HEAD方法响应

时间:2013-11-20 12:57:04

标签: scala playframework playframework-2.1

如何在scala play framework 2.1上返回唯一的响应头(HTTP HEAD方法)?

3 个答案:

答案 0 :(得分:0)

您可以在GET路线旁边添加HEAD路线,如下所示:

GET   /assertion                        controllers.Assertion.get
HEAD  /assertion                        controllers.Assertion.head

在实现方法中,我猜你可以调用GET方法并传递一个标志来压制身体。

答案 1 :(得分:0)

如何将EmptyContent作为内容返回

     Action {
        ....
        Ok(EmptyContent())  
     }

答案 2 :(得分:0)

不幸的是有Java解决方案,但也许你会将它“转换”为Scala,一般概念是:

  • 抓住HEAD请求将其发送到专用方法
  • 方法autoHead(String originalPath)使用WebServices转发参数发送GET请求,并仅返回响应的状态。
  • 它会添加额外的标头X_FORWARD_FROM_HEAD,因此,如果您的操作在每次点击后都记录了数据库,则可以避免HEAD次请求。

<强>码

/**
 * Tries to get headers of resource with WebServices and return headers only.
 *
 * @param originalPath Path of the resource
 * @return Headers for HEAD request
 * @throws IllegalAccessException
 */
public static Result autoHead(String originalPath) throws IllegalAccessException {


    WS.WSRequestHolder forwardedRequest = WS.url("http://" + request().host() + request().path());
    // this header will allow you to make additional choice i.e. avoid tracking the request or something else
    // see condition in index() action
    forwardedRequest.setHeader("X_FORWARD_FROM_HEAD", "true");

    // Forward original headers
    for (String header : request().headers().keySet()) {
        forwardedRequest.setHeader(header, request().getHeader(header));
    }

    // Forward original queryString
    for (String key : request().queryString().keySet()) {
        for (String val : request().queryString().get(key)) {
            forwardedRequest.setQueryParameter(key, val);
        }
    }

    // Call the same path but with GET
    WS.Response wsResponse = forwardedRequest.get().get();

    // Set returned headers to the response
    for (Field f : Http.HeaderNames.class.getFields()) {
        String headerName = f.get(null).toString();
        if (wsResponse.getHeader(headerName) != null) {
            response().setHeader(headerName, wsResponse.getHeader(headerName));
        }
    }

    return status(wsResponse.getStatus());
}

/**
 * Checks if request if forwarded from HEAD request
 *
 * @return true if 'X_FORWARD_FROM_HEAD' header exists and is set to true
 */
public static boolean forwardedFromHead() {
    return (request().getHeader("X_FORWARD_FROM_HEAD") != null && "true".equals(request().getHeader("X_FORWARD_FROM_HEAD")));
}

<强>路线:

HEAD    /                  controllers.Application.autoHead(originalPath:String ?= "/")
HEAD    /*originalPath     controllers.Application.autoHead(originalPath:String)