Java™ API for
RESTful Web Services (JAX-RS) では、Request オブジェクトを使用して要求ヘッダーにアクセスできます。Request オブジェクトは、要求ヘッダーに基づいて前提条件を評価し、最適の応答バリアントを選択する手段を提供します。
このタスクについて
JAX-RS ランタイム環境に注入された Request オブジェクトを使用すると、HTTP ヘッダーの前提条件を簡単に評価できます。@javax.ws.rs.core.Context アノテーションは、コンテキスト・オブジェクトが注入されたことを示します。javax.ws.rs.core.Request は、注入対象となるオブジェクトのインターフェースです。注入された Request オブジェクトは、If-Modified-Since 値などの日付や If-Match などのエンティティー・タグを含む HTTP ヘッダー前提条件の評価に役立ちます。
Request オブジェクトは、拡張されたコンテンツ・ネゴシエーションの実装時にも使用できます。
コンテンツ・ネゴシエーションについて詳しくは、JAX-RS アプリケーションの要求および応答における XML コンテンツの使用に関する項を参照してください。
トラブルの回避 (Avoid trouble): HTTP ヘッダーで使用された日付の細分度は、データ・ソースで使用される一部の日付ほど正確ではありません。例えば、データベース行に含まれる日付はミリ秒単位で定義されている場合があります。
しかし、HTTP ヘッダー・フィールドの日付は秒単位にとどまります。HTTP の前提条件を評価する場合、java.util.Date オブジェクトを HTTP ヘッダーの日付と比較すると、精度の差によって予期せぬ結果が生まれることがあります。このような問題を回避するには、java.util.Date オブジェクトを正規化してから HTTP ヘッダーの日付値と比較してください。
gotcha
手順
- リソース・メソッドのシグニチャーが変更可能ならば、@javax.ws.rs.core.Context javax.ws.rs.core.Request パラメーターをメソッドに追加します。 リソース・メソッドが呼び出されると、JAX-RS ランタイム環境は Request オブジェクトを実装するオブジェクトを渡します。例:
@Path("/contextexample")
public class RootResource {
@GET
@Produces("text/plain")
public Response getResource(@Context Request requestObj) {
Date lastModified = /* Gets the last modified date of this resource from a data source. */;
ResponseBuilder possibleResponse = requestObj.evaluatePreconditions(lastModified);
/* If the preconditions are not met, then ResponseBuilder is not null. Return the automatically generated response. */
if (possibleResponse != null) {
return possibleResponse.build();
}
return Response.ok("a resource representation").lastModified(lastModified).build();
}
}
- リソース・メソッドのシグニチャーを変更できず、クラスがルート・リソースである場合、@javax.ws.rs.core.Context javax.ws.rs.core.Request フィールドを追加します。 リソースが要求に対してインスタンス化されると、Request を実装するオブジェクトが注入されます。例:
@Path("/contextexample")
public class RootResource {
@Context
Request requestObj;
@GET
@Produces("text/plain")
public Response getResource() {
Date lastModified = /* Gets the last modified date of this resource from a data source */;
ResponseBuilder possibleResponse = requestObj.evaluatePreconditions(lastModified);
/* If the preconditions are not met, then ResponseBuilder is not null. Return the automatically generated response */
if (possibleResponse != null) {
return possibleResponse.build();
}
return Response.ok("a resource representation").lastModified(lastModified).build();
}
}
タスクの結果
javax.ws.rs.core.Request オブジェクトを使用して、着信要求の HTTP ヘッダーを評価し、要求に対する適切な応答が判断できました。