O'Reilly logo

Java SOA Cookbook by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 representation 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 resource 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 programmatically. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required