为什么注入的UriInfo使用与注入HttpServletRequest不同的主机名?

时间:2013-02-04 04:17:21

标签: jax-rs hateoas apache-tomee cxfrs

我正在学习JAX-RS,并且喜欢将URL返回到响应中的其他相关操作。使用Apache TomEE JAX-RS 1.5.1,由于某种原因,注入的UriInfo实例提供的URL始终使用“localhost”作为主机名。

我添加了@Context HttpServletRequestgetLocalNamegetServerName值都与公共主机名匹配。因此,此信息应该可供与TomEE捆绑在一起的CXF-RS运行时使用。目前尚不清楚为何没有使用它。

下面是测试类和示例输出。如何让TomEE的嵌入式CXF-RS使用正确的主机名?或者,如果这不是正确的方法,我应该如何构建我可以在JAX-RS响应中返回的URL?

@Path("")
public class Test {

    @GET
    @Produces({MediaType.TEXT_PLAIN})
    public String defaultPage(@Context UriInfo uriInfo,
            @Context HttpHeaders hh,
            @Context HttpServletRequest httpServletRequest) {

        StringBuilder response = new StringBuilder();

        response.append("uriInfo.getAbsolutePath(): ");
        response.append(uriInfo.getAbsolutePath());
        response.append("\n");

        response.append("uriInfo.getBaseUri(): ");
        response.append(uriInfo.getBaseUri());
        response.append("\n");

        // snip the repetitive part...

        response.append("httpServletRequest.getServerPort(): ");
        response.append(httpServletRequest.getServerPort());
        response.append("\n\n");

        for (String header : hh.getRequestHeaders().keySet()) {
            response.append(header);
            response.append(":\n");

            for (String value : hh.getRequestHeaders().get(header)) {
                response.append("\t");
                response.append(value);
                response.append("\n");
            }
        }

        return response.toString();
    }

}

这是输出:

uriInfo.getAbsolutePath(): http://localhost:8081/sample-app-1.0-SNAPSHOT/
uriInfo.getBaseUri(): http://localhost:8081/sample-app-1.0-SNAPSHOT
uriInfo.getRequestUri(): http://localhost:8081/sample-app-1.0-SNAPSHOT/
httpServletRequest.getLocalAddr(): 1.2.3.4
httpServletRequest.getLocalName(): www.example.com
httpServletRequest.getLocalPort(): 8081
httpServletRequest.getServerName(): www.example.com
httpServletRequest.getServerPort(): 8081

Accept:
    text/html
    application/xhtml+xml
    application/xml;q=0.9
    */*;q=0.8
accept-encoding:
    gzip
    deflate
accept-language:
    en-us
cache-control:
    max-age=0
connection:
    keep-alive
Content-Type:
host:
    www.example.com:8081
user-agent:
    Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.17 (KHTML
    like Gecko) Version/6.0.2 Safari/536.26.17

0 个答案:

没有答案