How to access multiple resources in a single request : Jersey Rest

邮差的信 提交于 2019-12-25 04:15:44

问题


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")

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

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.


回答1:


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.



来源:https://stackoverflow.com/questions/7391995/how-to-access-multiple-resources-in-a-single-request-jersey-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!