Subresource Locator
JAX-RS では @Path
アノテーションでリクエストURLを、@GET
などのアノテーションで HTTPメソッドをマッピングします。
HTTPメソッドを指定するアノテーションを付けず、@Path
アノテーションだけを定義し、戻り値としてリソースクラスを返すメソッドは、Subresource Locator になります。
例えば以下のようなリソースです。
@Path("/item") public class ItemResource { @Path("content") public ItemContentResource getItemContentResource() { return new ItemContentResource(); } }
getItemContentResource()
は戻り値として ItemContentResource
リソースクラスを返却します。
ItemContentResource
リソースクラスでは以下のようにHTTPメソッドを @GET
などのアノテーションで指定します。
public class ItemContentResource { @GET public Response get() { ... } @PUT @Path("{version}") public void put(@PathParam("version") int version) { ... } }
GET /item/content
というリクエストにより ItemContentResource#get()
が呼び出されます。
PUT /item/content/3
というリクエストにより ItemContentResource#put()
が呼び出されます。
Subresource Locator による動的ディスパッチ
Subresource Locator を利用することにより、リソースを Runtime 時に動的にディスパッチすることができます。
この場合、Subresource Locator メソッドは Object 型を返却するように定義できます。
@Path("customers") public class CustomerResource { CustomerJsonResource jsonResource = new CustomerJsonResource(); CustomerXmlResource xmlResource = new CustomerXmlResource(); @Path("{type}") public Object getResource(@PathParam("type") String type) { if (type.equals("json")) { return jsonResource; } else if (type.equals("xml")) { return xmlResource; } return null; } }
Json 形式を返却するリソース、xml 形式を返却するリソースをそれぞれ定義します。
public class CustomerJsonResource { @GET @Path("{id}") @Produces({MediaType.APPLICATION_JSON}) public Customer get(@PathParam("id") Long id) { return findCustomer(id); } }
同様に、
public class CustomerXmlResource { @GET @Path("{id}") @Produces({MediaType.APPLICATION_XML}) public Customer get(@PathParam("id") Long id) { return findCustomer(id); } }
GET /customers/json/999
というリスエストにはjson形式でレスポンス、 GET /customers/xml/999
というリスエストにはxml形式でレスポンス、と動的に処理を切り替えることができます。
また、ResourceMethod.Builder
を使えば、リソースメソッドをプログラマティックに作成することができるため、Subresource Locator メソッドから、動的に作り上げたリソースメソッドを返却することもできます。
- 作者: Bill Burke,arton,菅野良二
- 出版社/メーカー: オライリージャパン
- 発売日: 2010/08/23
- メディア: 大型本
- 購入: 28人 クリック: 804回
- この商品を含むブログ (41件) を見る
Developing Restful Services With Jax-rs2, Json, and Websockets
- 作者: Bhakti Mehta,Masoud Kalali
- 出版社/メーカー: Packt Publishing
- 発売日: 2013/10/15
- メディア: ペーパーバック
- この商品を含むブログを見る