1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JAX-RS (Jersey) Tips

Last updated at Posted at 2019-08-15

パラメータをリソースクラスのメンバで受け取る

@HeaderParam, @PathParam, @QueryParam は各リソースメソッドで個々に定義する以外にも、コンストラクタに依存注入してリソースクラスのメンバに格納できる(リソースクラスがSingletonでない場合)。

ただし、ボディ(エンティティ)や@FormParam(ボディを参照する)はコンストラクタへの注入はできず、リソースメソッドの引数で受け取る必要がある。

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

HttpServletRequestを使わずにHTTPリクエストの情報にアクセスする

リソースメソッドの中で、生に近いHTTPリクエスト情報(HTTPメソッドやパス、クエリパラメータ、ヘッダ、ストリーム形式のボディ)を参照するには、HttpServletRequest を依存注入して使うのが簡単である。

class Resource {
	@Inject
	private HttpServletRequest request;
}

ただしこの方法はServletコンテナに依存するため、JAX-RS APIでやりくりするには以下のようにすればよい。

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

  public Response post(InputStream body) {
    // HTTPメソッド
    request.getMethod();
    // パス
    uriInfo.getPath();
    // クエリパラメータ
    uriInfo.getQueryParameters();
    // ヘッダ
    httpHeaders.getRequestHeaders();
    // ボディ(InputStream)
    body;
    ...
  }
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?