从JAX-RS资源中获取HTTP URL

Mar*_*tus 3 jax-rs jersey tomcat7

从我的JAX-RS(Jersey)资源内部,我需要获取Jersey Servlet"发布"该资源的基本URL .我ServletContext按照这里描述尝试注射,然后执行:

return servletContext.getResource("/").toString();
Run Code Online (Sandbox Code Playgroud)

获取Servlet此资源的Jersey的"基本"URL .

但是,上面的代码返回一个值,如:

jndi:/localhost/jax-rs-tomcat-test/
Run Code Online (Sandbox Code Playgroud)

我期待更多的东西:

http://localhost:8080/jax-rs-tomcat-test/jax-rs
Run Code Online (Sandbox Code Playgroud)

" jax-rs"是我在web.xml中的位置:

<servlet-mapping>  
   <servlet-name>jersey-servlet</servlet-name>  
   <url-pattern>/jax-rs/*</url-pattern>  
</servlet-mapping> 
Run Code Online (Sandbox Code Playgroud)

也就是说,存在四个"差异":(a)协议,(b)协议之后的单个而不是双斜杠,(c)端口号和(d)用于触发Jersey servlet的URL模式缺失.那么,我该怎么做:

  1. http://Jersey servlet 的基本URL
  2. 触发特定@GET或带@POST注释方法的完整URL ?

Mic*_*dos 11

您正在寻找UriInfo.使用@Context以下方法将其注入资源:

@Context
private UriInfo uriInfo;
Run Code Online (Sandbox Code Playgroud)

然后你可以调用getBaseUri()方法:

uriInfo.getBaseUri();
Run Code Online (Sandbox Code Playgroud)