2016-11-04 89 views
0

我想知道是否可以在dropwizard中从另一个资源类中调用另一个资源方法类。Dropwizard资源类调用另一个资源方法类?

我环顾了其他帖子,使用ResourceContext允许从另一个资源类调用get方法,但也可以使用其他资源类的post方法。

假设我们有两个资源类A和B.在类A中,我创建了一些JSON,并且我想使用B的post方法将该JSON发布到B类。这可能吗?

+0

你想从A调用一个B的方法吗?当然,您可以像其他方法调用一样执行该操作,但是您需要在A中拥有B实例。如果您想对另一个URL(B)进行HTTP POST调用,则可以使用httpclient(球衣或例如apache httpclient)。或者干脆你可以有一个重定向http://stackoverflow.com/questions/20709386/dropwizard-how-to-do-a-server-side-redirect-from-a-view – gaganbm

回答

3

是,资源上下文可以用于从相同或不同资源中的另一种方法访问POSTGET方法。
@Context的帮助下,您可以轻松访问这些方法。

@Path("a") 
class A{ 
    @GET 
    public Response getMethod(){ 
     return Response.ok().build(); 
    } 
    @POST 
    public Response postMethod(ExampleBean exampleBean){ 
     return Response.ok().build(); 
    } 
} 

现在,您可以从Resource B访问下列方式Resource A的方法。

@Path("b") 
class B{ 
    @Context 
    private javax.ws.rs.container.ResourceContext rc; 

    @GET 
    public Response callMethod(){ 
     //Calling GET method 
     Response response = rc.getResource(A.class).getMethod(); 

     //Initialize Bean or paramter you have to send in the POST method 
     ExampleBean exampleBean = new ExampleBean(); 

     //Calling POST method 
     Response response = rc.getResource(A.class).postMethod(exampleBean); 

     return Response.ok(response).build(); 
    } 
}