create a Jax-RS RESTful service that accepts both POST and GET?

喜欢而已 提交于 2019-12-05 06:02:49

As wikipedia says, an API is RESTful if it is a collection of resources with four defined aspects:

  • the base URI for the web service, such as http://example.com/resources/
  • the Internet media type of the data supported by the web service. This is often XML but can be any other valid Internet media type providing that it is a valid hypertext standard.
  • the set of operations supported by the web service using HTTP methods (e.g., GET, PUT, POST, or DELETE).
  • The API must be hypertext driven.

By diminishing the difference between GET and POST you're violating the third aspect.

Just put your method body in another method and declare a public method for each HTTP verb:

@Controller
@Path("/foo-controller")
public class MyController {

    @GET
    @Path("/thing")
    public Response getStuff() {
        return doStuff();
    }

    @POST
    @Path("/thing")
    public Response postStuff() {
        return doStuff();
    }

    private Response doStuff() {
        // Do the stuff...
        return Response.status(200)
                .entity("Done")
                .build();
    }
}

If this scenario fits for all your resources you could create a ServletFilter which wraps the request and will return Get or Post everytime the method will be requested.

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