3

With given Application

@ApplicationPath("/api")
public class MyApplication {
}

UriInfo#getBaseUri gives me an application path.

@Context
private UriInfo uriInfo

uriInfo.getBaseUri(); // http://address/<context-path>/api

How can I get context-path? How can I get full URL to context-path?

http://address/<context-path>

UPDATE

I currently using code from this answer.

@Context
private HttpServletRequest servletRequest;

final URI contextUri
     = URI.create(servletRequest.getRequestURL().toString())
    .resolve(servletRequest.getContextPath());

Any other suggestions?

Community
  • 1
  • 1
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

2 Answers2

7

To get application context, you can inject the ServletContext in your REST method and retrieve contextPath from it, for example like this:

@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Catalog find(@PathParam("id") Long id, @Context ServletContext servletContext) {
    String contextPath = servletContext.getContextPath();
    ...
}

EDIT

To get the "full URL to context-path" you want. You could also inject the HttpServletRequest with @Context annotation and use getScheme(), getServerName() and getServerPort() methods to build it.

yurez
  • 2,826
  • 1
  • 28
  • 22
Rémi Bantos
  • 1,899
  • 14
  • 27
4

One possible way is using HttpServletRequest.

@Context
private HttpServletRequest servletRequest;

final URI contextUri
     = URI.create(servletRequest.getRequestURL().toString())
    .resolve(servletRequest.getContextPath());
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184