RESTful Web Services Developer's Guide

Deploying a RESTful Web Service

This section is taken from the document titled Overview of JAX-RS 1.0 Features.

JAX-RS provides the deployment-agnostic abstract class Application for declaring root resource classes and root resource singleton instances. A Web service may extend this class to declare root resource classes, as shown in the following code example.

public class MyApplicaton extends Application {
    public Set<Class<?>> getClasses() {
        Set<Class<?>> s = new HashSet<Class<?>>();
        s.add(HelloWorldResource.class);
        return s;
    }
}

Alternatively, it is possible to reuse a Jersey implementation that scans for root resource classes given a classpath or a set of package names. Such classes are automatically added to the set of classes that are returned by the getClasses method. For example, the following code example scans for root resource classes in packages org.foo.rest, org.bar.rest, and in any their sub-packages.

public class MyApplication extends PackagesResourceConfig {
    public MyApplication() {
        super("org.foo.rest;org.bar.rest");
    }
}

For servlet deployments, JAX-RS specifies that a class that implements Application may be declared instead of a servlet class in the <server-class> element of the application deployment descriptor, web.xml. As of this writing, this is not currently supported for Jersey. Instead it is necessary to declare the Jersey-specific servlet and the Application class, as shown in the following code example.

<web-app>
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>MyApplication</param-value>
        </init-param>
    </servlet>
    ....

An even simpler approach is to let Jersey choose the PackagesResourceConfig implementation automatically by declaring the packages as shown in the following code.

<web-app>
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>org.foo.rest;org.bar.rest</param-value>
        </init-param>
    </servlet>
    ....

JAX-RS also provides the ability to obtain a container-specific artifact from an Application instance. In the following code example, Jersey supports using Grizzly.

SelectorThread st = 
	RuntimeDelegate.createEndpoint(new MyApplication(), 
	SelectorThread.class);

Jersey also provides Grizzly helper classes to deploy the ServletThread instance at a base URL for in-process deployment. The Jersey samples provide many examples of servlet-based and Grizzly-in-process-based deployments.