I'm learning JAX-RS, and like the idea of returning URLs to other relevant actions in a response. Using Apache TomEE JAX-RS 1.5.1, for some reason the URLs provided by an injected UriInfo
instance are always using "localhost" as the host name.
I added a @Context HttpServletRequest
, and the getLocalName
and getServerName
values both matched the public host name. So this information should be available to the CXF-RS runtime bundled with TomEE. It's just not clear why it isn't being used.
Below is the test class, and sample output. How can I get TomEE's embedded CXF-RS to use the correct hostname? Or, if that isn't the right approach, how should I be building URLs that I can return in JAX-RS responses?
@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();
}
}
And here is the output:
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