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

I am converting one of my existing services to become RESTful, and I have the basic things that work with RestEasy. Some of my client applications should be able to execute both GET and POST requests to multiple services. I'm just looking if there is any easy way for jax-rs to indicate that the API should accept both GET and POST. After you can find the testing method, let me know if you see any way without duplicating it in another class using @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(); } 
+4
source share
3 answers

Like wikipedia , the RESTful API, if it is a set of resources with four specific aspects:

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

Reducing the difference between GET and POST , you violate the third aspect.

+4
source

Just put the 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(); } } 
+16
source

If this script is suitable for all of your resources, you can create a ServletFilter that wraps the request and will return Get or Post every time the method is requested.

0
source

Source: https://habr.com/ru/post/1446347/


All Articles