如何在一个请求中访问多个资源:Jersey Rest [英] How to access multiple resources in a single request : Jersey Rest

查看:111
本文介绍了如何在一个请求中访问多个资源:Jersey Rest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为以下情况找到一个好的设计. 我有一个POST rest服务,该服务将作为数据提供一系列服务.然后依次调用它们,以在服务器上汇总结果并将其发送回客户端.

I am trying to a find a good design for the following scenario. I have a POST rest service which will be given an array of services as data. And which should in turn be calling them one by one to aggregate results on the server and send them back to the client.

@Path("/resource1") @Path("/resource2") @Path("/collection")

@Path("/resource1") @Path("/resource2") @Path("/collection")

Post data to /collection {["serviceName": "resource1", "data":"test1"], ["serviceName":"resource2","data":"test2"]}

Post data to /collection {["serviceName": "resource1", "data":"test1"], ["serviceName":"resource2","data":"test2"]}

之所以需要resource1和resource2是因为这些服务也可以称为独立服务.如果可能,我想重用相同的设置. 有什么办法可以做到这一点. 我在春季使用球衣.

The reason i need the resource1 and resource2 are, because those services can be called standalone also. I want to reuse the same setup if possible. Is there any way to do this. I am using jersey with spring.

推荐答案

不确定这些资源有何共同之处.如果post方法对所有对象都具有相同的签名,则可以让它们实现定义post方法的抽象类或接口,并可以尝试使用ResourceContext.matchResource做到这一点.例如.像这样的东西:

Not sure what these resources have in common. If the post method has the same signature for all of them, you could have an abstract class or interface they implement defining the post method and can try using ResourceContext.matchResource to do this. E.g. something like this:

public abstract class AbstractResource {
    public abstract String post(Object data);
}

@Path("/resource1")
public class Resource1 extends AbstractResource {
    @POST
    public String post(String data) {
        // do something
    }
}

@Path("/collection")
public class CollectionResource {
    @Context
    private ResourceContext rc;

    @POST
    @Consumes("application/json")
    public String post(List<PostRequest> postRequests) {
        StringBuilder result = new StringBuilder();
        for (PostRequest pr : postRequests) {
            // should wrap this in try-catch
            AbstractResource ar = rc.matchResource(pr.resource,
                    AbstractResource.class);
            sb.append(ar.post(pr.data));
        }
        return result.toString();
    }
}

@XmlRootElement
public class PostRequest {
    public String resource;
    public String data;
}

希望您已经有了这个主意,并且可以对其进行调整并进行调整以满足您的需求.

Hopefully you got the idea and will be able to play with it and tweak it to fit your needs.

这篇关于如何在一个请求中访问多个资源:Jersey Rest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆