Java Reference
In-Depth Information
Creating a Resource
Problem
You want to provide a way for users to create a RESTful resource in JAX-RS.
Solution
Use the @POST annotation on a resource method to indicate that it accepts HTTP POST data,
and add the entity in the method with the incoming data.
If you're not using JAX-RS, post the data from an HTML form. Create the URI for the new
resource, and return the proper set of links to allow users to perform any new state transitions
they might want. Remember not to store state on the server.
Discussion
In this example, you'll use the @POST annotation on a method to add a resource to the server,
and then retrieve it. Using POST to create data is common, though PUT may sometimes be
used. POST is the more common idiom because HTML works readily with it, even though
PUT may make more sense conceptually.
An HTTP POST response in REST will result in a 201 response (typically including a repres-
entation indicating what happened and offering another idea of what states you can transition
to next). Some designers might choose to have a POST result in a 204 status code that includes
a location header containing the URI of the new resource.
NOTE
Strictly speaking, the HTTP status code 201 means that the request has been fulfilled and a new re-
source has been created. 204 means the request has been fulfilled and produces a response of No
Content, meaning it does not include a message body. So 201 is preferred here.
In this example, you'll use the Apache Commons HTTP Client to do post data programmatic-
ally. First you'll create a service using JAX-RS, and then create the client that can add entities
and get them later.
Example 8-16 shows the code for the service.
Example8-16.Post and get user service
Search WWH ::




Custom Search