简体   繁体   English

JAX-RS球衣-Web服务资源合作

[英]JAX-RS Jersey - Web service resources cooperation

I am implementing a restful web service using Jersey (Jax-rs). 我正在使用Jersey(Jax-rs)实现一个宁静的Web服务。

I have two resources: 我有两个资源:

/news : returns a list of news / news :返回新闻列表

/countries : returns a list of countries / countries :返回国家列表

And I want to implement something to allow me to get the news of a certain country. 我想采取一些措施使我能够了解某个国家的新闻。

Something like : /countries/{countryId}/news 类似于: / countries / {countryId} / news

How, and where I should implement it? 如何以及在哪里实施?

News Resource Code: 新闻资源代码:

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

    NewsService newsService = new NewsService();

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

}

Countries Resource Code: 国家资源代码:

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

    CountriesService countriesService = new CountriesService();

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

}

I can do it by adding the following method to the Countries class. 我可以通过在Countrys类中添加以下方法来做到这一点。

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

But, this way, my Countries resource is returning news, which I don't find logical! 但是,通过这种方式,我的国家/地区资源正在返回新闻,我认为这不合逻辑!

Here comes the solution: 解决方案如下:

News Resource Code: 新闻资源代码:

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

}

Countries Resource Code: 国家资源代码:

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

}

When calling /news since countryId is null, we get all news. 由于countryId为null时调用/ news时 ,我们会获得所有新闻。

When calling countries/{countryId}/news , we call the news resource from the countries resource, and since countryId contains the id of the country for which we want to get the news, we call the getCountryNews(countryId) method. 在调用国家/ {countryId} / news时 ,我们从国家资源中调用新闻资源,并且由于countryId包含我们要获取新闻的国家/地区的ID,因此我们调用getCountryNews(countryId)方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM