2017-03-29 14 views
0

私はJersey(Jax-rs)を使用して快適なWeb​​サービスを実装しています。JAX-RS Jersey - Webサービスリソース協力

私は2つのリソースがあります。

/ニュース:ニュース

/国のリストを返します:国

のリストを返し、私は私を可能にするために何かを実装したいと特定の国のニュースを入手する。

のような何か:/国/ {countryId} /ニュース

どのように、と私はそれを実装する必要がありますか?

ニュースリソースコード:

@Path("/news") 
public class NewsResource { 

    NewsService newsService = new NewsService(); 

    @GET 
    @Produces(MediaType.APPLICATION_JSON) 
     public List<News> getNews(){ 
      return newsService.getNews(); 
    } 

} 

国リソースコード:

@Path("/countries") 
public class CountriesResource { 

    CountriesService countriesService = new CountriesService(); 

    @GET 
    @Produces(MediaType.APPLICATION_JSON) 
     public List<Countries> getCountries(){ 
      return countriesService.getCountries(); 
    } 

} 

私はクラスに次のメソッドを追加することによって、それを行うことができます。

@Path("/{countryId}/news") 
    @Produces(MediaType.APPLICATION_JSON) 
    public List<News> getCountryNews(@PathParam("countryId") int countryId){ 
     return countryService.getCountryNews(countryId); 
    } 

しかし、この方法で、私のリソースは、私は論理的な見つけることはありませんこれは、ニュースを返して!ここで

答えて

0

は解決策を来る:

ニュースリソースコード:

@Path("/news") 
public class NewsResource { 

    NewsService newsService = new NewsService(); 

    @GET 
    public List<News> getNews(@PathParam("countryId") int countryId){ 
     if(countryId==null){ 
      return newsService.getNews(); 
     }else{ 
      return newsService.getCountryNews(countryId); 
     } 
    } 

} 

国リソースコード:

@Path("/countries") 
public class CountriesResource { 

    CountriesService countriesService = new CountriesService(); 

    @GET 
    @Produces(MediaType.APPLICATION_JSON) 
     public List<Countries> getCountries(){ 
      return countriesService.getCountries(); 
    } 

    @Path("/{countryId}/news") 
    public NewsResource getCountryNews(){ 
     return new CountryResource(); 
    } 

} 

countryId 以来/ニュースを呼び出しますがnullの場合、すべてのニュースを取得します。

国/ {countryId} /ニュースを呼び出すとき、私たちはリソースからニュースリソースを呼び出し、以来countryIdたちがニュースを取得したい国のIDが含まれていますgetCountryNews(countryId)メソッドと呼びます。

関連する問題