Reputation: 2049
I have a WAR file that i run in Tomcat. This WAR contains a number of html pages that are served from (For testing purposes) http://localhost:port/testapp/somepage.html
.
Included in this app is also a CXF REST service endpoint, which is hosted at http://localhost:port/testapp/cxf/
with a few services like http://localhost:port/testapp/cxf/getlink
The getlink method service should return a link to one of the html pages. I don't want to statically set the context path in the code or in a configuration file, as i have no control over what context path the application will be hosted at.
So what i want to do is get the context path during runtime. How do i do this?
I have tried the following (Notice the @Path("/")
the "cxf" part of the path comes from the web.xml and it is the CXF servlets path)
@Path("/")
public class TestEndpoint {
...
@Context
UriInfo uri;
@GET
@Path("/getlink")
public Response giveMeXML(@Context Request context) {
URI baseURI = UriBuilder.fromUri(uri.getBaseUri()).replacePath("").build();
....
}
I expected UriInfo.getBaseUri()
to give me an URI containing the "scheme://host:port/contextpath" of my application, but it doesn't. It returns
"scheme://host:port/contextpath/cxf-app-path" like http://localhost:8080/testapp/cxf
How do i get the context path that the WAR is deployed under, in the REST endpoint? What is want is to somehow get the context path that the WAR is deployed under, like: http://localhost:8080/testapp/
.
Upvotes: 1
Views: 2437
Reputation: 209092
Unfortunately, AFAICT, there is no single API to obtain this information. You will need to manually do it (with some string manipulation). One way is to inject the HttpServletRequest
and use its APIs to create the path. For example
@GET
public String getServletContextPath(@Context HttpServletRequest request) {
return getAbsoluteContextPath(request);
}
public String getAbsoluteContextPath(HttpServletRequest request) {
String requestUri = request.getRequestURL().toString();
int endIndex = requestUri.indexOf(request.getContextPath())
+ request.getContextPath().length();
return requestUri.substring(0, endIndex);
}
Upvotes: 1