6

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

我添加了一个@Context HttpServletRequest,getLocalNamegetServerName值都匹配公共主机名。因此,与 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
4

0 回答 0