java-ee Java RESTful Web Services (JAX-RS) Simple Resource

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

First of all for a JAX-RS application must be set a base URI from which all the resources will be available. For that purpose the javax.ws.rs.core.Application class must be extended and annotated with the javax.ws.rs.ApplicationPath annotation. The annotation accepts a string argument which defines the base URI.

@ApplicationPath(JaxRsActivator.ROOT_PATH)
public class JaxRsActivator extends Application {

    /**
     * JAX-RS root path.
     */
    public static final String ROOT_PATH = "/api";

}

Resources are simple POJO classes which are annotated with the @Path annotation.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/hello")
public class HelloWorldResource {
    public static final String MESSAGE = "Hello StackOverflow!";

    @GET
    @Produces("text/plain")
    public String getHello() {
        return MESSAGE;
    }
}

When a HTTP GET request is sent to /hello, the resource responds with a Hello StackOverflow! message.



Got any java-ee Question?