4

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:

  1. the base http:// URL of the Jersey servlet
  2. the full URL that triggered a particular @GET or @POST annotated method ?
Community
  • 1
  • 1
Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331

1 Answers1

11

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();
Michal Gajdos
  • 10,339
  • 2
  • 43
  • 42