create a Jax-RS RESTful service that accepts both

2019-05-01 17:15发布

问题:

I'm converting one of my existing service to become RESTful and I've got the basic things working with RestEasy. Some of my client apps should be able to execute both GET and POST requests to several services. I'm just seeking if there is any easy way around jax-rs to specify that API should accept both GETs and POSTs. Following you can find a test method, let me know if you see any way around without duplicating this in another class with @GET and @QueryParam.

@POST
@Path("/add")
public Response testREST(@FormParam("paraA") String paraA,
        @FormParam("paraB")  int paraB) {

    return Response.status(200)
            .entity("Test my input : " + paraA + ", age : " + paraB)
            .build();

}

回答1:

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.



回答2:

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


回答3:

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.