Can I use both @Post and @Get on the same method

回眸只為那壹抹淺笑 提交于 2019-12-05 19:39:21

问题


I would like to use both @Post and @Get on the same method like

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

Even I write like this, I got error. What I want is whatever get or post to the sameurl, the same method works. Is it possible? Now I separate two methods, one for get and one for post.


回答1:


Unfortunately, only one should be used in order to avoid Jersey exception. But you could do something like :

@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);
}

By doing so, if you want to change inner behavior of your functions, you will only have to change one function.

Note that method name in java for get vs post need to be different.




回答2:


After searching a lot trying to avoid the solution above, I found nothing....

Then I decided to create a custom annotation so I didn't have to waste time duplicating methods.

Here's the github link: Jersey-Gest

It allows you to create GET and Post Methods on a single Annotation by generating a new class from it.

I hope it helps you the same way it helped me :)

Edit:

If for some reason the above link stops working, here's what I did:

  • Created a compile-time annotation @RestMethod for class methods.
  • Created a compile-time annotation @RestClass for classes.
  • Create an AnnotationProcessor which generates a new class with Jersey's corresponding annotations and for each method creates a GET and a POST method which callsback to the original method annotated with @RestClass.

All methods annotated with @RestMethod must be static and contained within a class annotated with @RestClass.

Example (TestService.java):

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

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

}

Generates something like (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();
    }
}


来源:https://stackoverflow.com/questions/17338828/can-i-use-both-post-and-get-on-the-same-method

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