パラメータをリソースクラスのメンバで受け取る
@HeaderParam
, @PathParam
, @QueryParam
は各リソースメソッドで個々に定義する以外にも、コンストラクタに依存注入してリソースクラスのメンバに格納できる(リソースクラスがSingletonでない場合)。
ただし、ボディ(エンティティ)や@FormParam(ボディを参照する)はコンストラクタへの注入はできず、リソースメソッドの引数で受け取る必要がある。
class Resource {
Resource(@PathParam("path") String pathParam) { ... }
}
参考
- 3.5. Rules of Injection - Jersey 2.28 User Guide
- 2.12. Rules of Injection - Jersey 1.19.1 User Guide
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;
...
}
}