You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

Resources

Resources are one of the fundamental concepts in REST. REST emphasizes the manipulation of resources rather than issuing function calls. Resources have unique identifiers. In HTTP terms, this means associating every resource with at least one URL.

To manipulate a resource, requests are made with a specific HTTP method. For instance, to retrieve a representation of a resource, a HTTP GET request to the resource's URL is issued. To create a new item in a collection, a HTTP POST could be used with the collection URL.

Application developers can define resources and the HTTP methods to manipulate them very quickly by using regular plain old Java objects and JAX-RS annotations.

Define a Root Resource

Developers can use POJOs to define a resource. Root resources have a @Path annotation at the class declaration level. JAX-RS matches an incoming request's URL with the @Path annotation on all of an application's root resources to determine which initial Java class will handle the request.

To create Java methods that will be invoked with specific HTTP methods, implement a regular Java method and annotate it with one of the JAX-RS @HttpMethod annotations (namely, @GET, @POST, @PUT, and @DELETE).

For instance, if there's a resource that is at a "/welcome" URL, the following root resource could be defined.

WelcomeMessage.java
@Path("/welcome")
public class WelcomeMessage {
    private String welcomeMessage = "Hello world!";

    @GET
    public String returnWelcomeMessage() {
        return welcomeMessage;
    }
}

Any incoming GET request that has the URL of "/welcome" would be handled by WelcomeMessage class's returnWelcomeMessage() method. A string is returned which represents the response body. To return more complex response entities, see the Request/Response entities page.

HTTP Methods

There are well-defined HTTP methods that can be issued. The 4 most common are GET, POST, PUT, and DELETE.

As shown in the example above, a HTTP GET to "/welcome" would invoke the Java method returnWelcomeMessage(). To add a Java method that would be invoked when a HTTP PUT request is made to "/welcome", add the following code:

WelcomeMessageWithPut
@Path("/welcome")
public class WelcomeMessage {
    private String welcomeMessage = "Hello world!";

    @GET
    public String returnWelcomeMessage() {
        return welcomeMessage;
    }

    @PUT
    public String updateWelcomeMessage(String aNewMessage) {
        welcomeMessage = aNewMessage;
    }
}

Notice that the updateWelcomeMessage has an unannotated parameter which represents an incoming request's body. See the Request/Response entities page for more details on how request/response entities are handled.

  • No labels