JAX-RS Jersey - Web 服务资源合作



我正在使用Jersey(Jax-rs(实现一个宁静的Web服务。

我有两个资源:

/news : 返回新闻列表

/国家

/地区:返回国家/地区列表

我想实施一些东西,让我能够获得某个国家的新闻。

类似这样的内容:/国家/{国家 ID}/news

我应该如何以及在何处实施它?

新闻资源代码:

@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);
    }

但是,这样,我的国家资源正在返回新闻,我觉得这不合逻辑!

这是解决方案:

新闻资源代码:

@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();
    }
}

当调用 /news 时,因为 countryId 为空,我们得到所有新闻。

当调用 country/{countryId}/news 时,我们从 country 资源调用新闻资源,由于 countryId 包含我们要获取新闻的国家/地区的 ID,因此我们调用 getCountryNews(countryId( 方法。

最新更新