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
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
/foo/123
or/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