Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the HTTP URL from inside a JAX-RS resource

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 ?
like image 894
Marcus Junius Brutus Avatar asked Dec 20 '22 21:12

Marcus Junius Brutus


1 Answers

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();
like image 134
Michal Gajdos Avatar answered Feb 01 '23 23:02

Michal Gajdos