سؤال

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.
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

  1. There is a @PUT example on the Apache CXF http-binding page.

  2. Why use PUT? Well, in a RESTful application, you would want for example to implement an add/edit functionality for an entity, say, MyEntity.

    Now, the add would go on a link like: /myApplication/myEntity on the POST method, while the edit would go on /myApplication/myEntity/id, but on PUT. The GET request would also go on the previous link /myApplication/myEntity/id, and same goes for DELETE.

    You are basically providing CRUD operation support for MyEntity in a standard, straightforward way. Of course, you could do the PUT and DELETE operations through a POST, and that would also work.

    You can read more on RESTful webservices here, and more on PUT vs POST here.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top