From inside my JAX-RS (Jersey) resource I need to get the base URL of the Jersey Servlet
that's "publishing" that resource. I tried injecting ServletContext
as described here, and then doing a:
return servletContext.getResource("/").toString();
to get the "base" URL of the Jersey Servlet
for this resource.
However the above code returns a value like:
jndi:/localhost/jax-rs-tomcat-test/
where I was expecting something more like:
http://localhost:8080/jax-rs-tomcat-test/jax-rs
Where "jax-rs
" is what I have in my web.xml:
<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/jax-rs/*</url-pattern>
</servlet-mapping>
That is, there are four "differences": (a) protocol, (b) single instead of double slash after the protocol, (c) port number and (d) missing URL pattern for triggering the Jersey servlet. So, how do I get:
http://
URL of the Jersey servlet @GET
or @POST
annotated method ? You're looking for UriInfo. Inject it into your resource using @Context
:
@Context
private UriInfo uriInfo;
and then you can call getBaseUri()
method:
uriInfo.getBaseUri();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With