JAX-RS (Jersey) Tips

Receive parameters as members of resource class

In addition to defining @HeaderParam, @PathParam, and @QueryParam individually in each resource method, they can be injected dependently on the constructor and stored in the members of the resource class (if the resource class is not a Singleton).

However, body (entity) and @FormParam (reference body) cannot be injected into the constructor and must be received as an argument of the resource method.

class Resource {
    Resource(@PathParam("path") String pathParam) { ... }
}
reference

Access HTTP request information without using HttpServletRequest

In order to refer to HTTP request information (HTTP method, path, query parameter, header, stream format body) that is close to raw in the resource method, it is easy to use HttpServletRequest by dependency injection.

class Resource {
	@Inject
	private HttpServletRequest request;
}

However, this method depends on the Servlet container, so to manage with the JAX-RS API, do as follows.

class Resource {
  @Context Request request;
  @Context UriInfo uriInfo;
  @Context HttpHeaders httpHeaders;

  public Response post(InputStream body) {
    //HTTP method
    request.getMethod();
    //path
    uriInfo.getPath();
    //Query parameters
    uriInfo.getQueryParameters();
    //header
    httpHeaders.getRequestHeaders();
    //Body (InputStream)
    body;
    ...
  }
}

Recommended Posts

JAX-RS (Jersey) Tips
Java tips, tips
Rails Tips
Java Tips
Try deploying Zipkin in your Jersey (JAX-RS2) application