Deploying Jersey resources on Servlet 3.0 container
The common way to deploy a Jersey REST resource is to configure the web.xml
file so that there is a servlet container responsible to delegate requests from a specific URL pattern to resource classes. If you use a Servlet 3.0 container, for example Tomcat 7, it is possible to use Java annotations rather than a web.xml
file. Oddly enough, there is not much information available on how to configure Jersey by using annotations.
First, you need a class that extends class Application
and that has to be annotated with @ApplicationPath
. The value of the annotation is the base path of the REST service that is to be managed by this class. This class must override method getClasses
that returns a set of classes that provide the implementation of the endpoints of this REST service. This is comparable to the declaration of packages that was used previously in the web.xml
file.
1 2 3 4 5 6 7 8 9 10 11 12 13 | @ApplicationPath( "rest" ) public class RestService extends Application { public RestService( ) {} @Override public Set<Class<?>> getClasses( ) { final Set<Class<?>> returnValue = new HashSet<Class<?>>( ); returnValue.add( Resource.class ); return returnValue; } } |
Class Resource
implements the REST service and has to be annotated with @Path
on the class level. This is very important. If this annotation is missing, the REST service cannot be accessed.
1 2 3 4 5 6 7 8 9 10 11 12 | @Path( "/hello" ) public class Resource { public Resource( ) {} @GET @Produces( "text/html" ) public String printHelloWorld( ) { return "Hello World"; } } |
The URL to access the REST service is http://localhost:8080/api/rest/hello
, provided that api
is the path under which this project was deployed into the Tomcat container. When you open this URL in a Web browser, you should see the Hello World
message.