Search code examples
javaput

Handling Put requests on Java side


I have a dynamic web project where in I use apache cxf and HTTP. Now I've worked with POST and GET requests before.

On the java side, I'd use annotation @GET/@POST etc and from the UI I can make requests to it.

I was just reading about the PUT request and I am not able to place it just well in the above scenario. As much as I understand, PUT is used to add data or upload data. Now, what I don't understand is that

  1. How is PUT handled on java side. Can I please have an example here (link).
  2. Why use PUT? Even if I want to add some info, or upload, I can use POST for the same and then add it to my data source.

Solution

  • A HTTP PUT is handled by a method that is annotated with @PUT.

    @PUT
    @Path("/foo/{id}")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response putAFoo(@PathParam("id") int theId, Foo theFoo) {
      // Save theFoo which has theId or do what you want with it.
      if (fooWasCreated) {
        return Response.created("/foo/" + theId).build();
      } else {
        return Response.ok().build();
      }
    }
    

    Why use PUT? Usually PUT is used to change the server side state of a known resource. If you can address a resource by the comple URI, you can use this URI to GET a representation of it. You can also PUT to this URL with a new representation of the resource.

    PUT is also used to create a new resource if the ID is controlled by the server. A request

    PUT /foo/123
    

    can be used to

    1. overwrite /foo/123 or
    2. create /foo/123.

    That is different from POST which is usually requested on the collection resource.

    POST /foo/
    

    with the representation of a new resource would cause the server to assign an ID to the new resource. The server would then return a response like this:

    201 Created
    Location: /foo/456