10

我想在相同的方法上同时使用 @Post 和 @Get

@GET
@POST
@Path("{mode}")
public void paymentFinish(@PathParam("mode") String mode, String s) {
    logger.debug("Enter PayStatus POST");
    logger.debug(mode);
}

即使我这样写,我也有错误。我想要的是获取或发布到相同的网址,相同的方法有效。可能吗?现在我将两种方法分开,一种用于获取,一种用于发布。

4

2 回答 2

14

不幸的是,为了避免 Jersey 异常,应该只使用一个。但是您可以执行以下操作:

@GET
@Path("{mode}")
public void paymentFinish(@PathParam("mode") String mode, String s) {
    commonFunction(mode);
}

@POST
@Path("{mode}")
public void paymentFinishPOST(@PathParam("mode") String mode, String s) {
    commonFunction(mode);
}

private void commonFunction(String mode)
{
    logger.debug("Enter PayStatus POST");
    logger.debug(mode);
}

通过这样做,如果你想改变你的函数的内部行为,你只需要改变一个函数。

请注意,Java 中 get 与 post 的方法名称需要不同。

于 2013-06-27T15:48:28.097 回答
1

在搜索了很多试图避免上述解决方案之后,我什么也没找到......

然后我决定创建一个自定义注释,这样我就不必浪费时间复制方法了。

这是 github 链接:Jersey-Gest

它允许您通过从中生成新类来在单个注释上创建 GET 和 Post 方法。

我希望它能像帮助我一样帮助你:)

编辑:

如果由于某种原因上述链接停止工作,这就是我所做的:

  • 为类方法创建了一个编译时注解@RestMethod 。
  • 为类创建了一个编译时注释@RestClass
  • 创建一个 AnnotationProcessor ,它使用 Jersey 的相应注释生成一个新类,并为每个方法创建一个GET和一个POST方法,该方法回调到使用@RestClass注释的原始方法。

所有使用@RestMethod注释的方法必须是静态的,并且包含在使用@RestClass注释的类中。

示例(TestService.java):

@RestClass(path = "/wsdl")
public class TestService
{

    @RestMethod(path = "/helloGest")
    public static String helloGest()
    {
        return "Hello Gest!";
    }

}

生成类似(TestServiceImpl.java)的东西:

@Path("/wsdl")
@Produces("application/xml")
public class TestServiceImpl
{
    @GET
    @Path("/helloGest")
    @Produces(MediaType.APPLICATION_XML)
    public String helloGestGet()
    {
        return TestService.helloGest();
    }

    @POST
    @Path("/helloGest")
    @Consumes(MediaType.WILDCARD)
    @Produces(MediaType.APPLICATION_XML)
    public String helloGestPost()
    {
        return TestService.helloGest();
    }
}
于 2014-07-04T03:04:03.723 回答