开发者

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

开发者 https://www.devze.com 2023-04-04 20:57 出处:网络
I am trying to a find a good design for the following scenario. I have a POST rest serv开发者_StackOverflowice which will be given an array of services as data. And which should in turn be calling the

I am trying to a find a good design for the following scenario. I have a POST rest serv开发者_StackOverflowice 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消