JAX-RS using Jersey and Maven on Tomcat 7
Create a basic Maven project called RestTest with no archetype in Eclipse. Add the dynamic web project facet to your project and let Eclipse generate a default web.xml
file for you. Then add the following Jersey dependencies to your pom.xml
:
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.17.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.17.1</version>
</dependency>
</dependencies>
And the following servlet and servlet mapping to your web.xml
:
<servlet>
<servlet-name>JAX-RS Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS Servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Now lets create a very basic JAX-RS service:
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/")
public class CatService {
@Path("cats")
@GET
@Produces("application/json; charset=UTF-8")
public List<Cat> getCats() {
final Cat cat1 = new Cat("Julien", 2);
final Cat cat2 = new Cat("Tom", 6);
final List<Cat> cats = new ArrayList<Cat>();
cats.add(cat1);
cats.add(cat2);
return cats;
}
}
And a small model class:
public class Cat {
public String name;
public int age;
public Cat(final String name, final int age) {
this.name = name;
this.age = age;
}
}
Now add the application to Tomcat and start the server. On startup you should see something like this in your console:
Apr 08, 2013 4:26:28 PM com.sun.jersey.api.core.servlet.WebAppResourceConfig init
INFO: Scanning for root resource and provider classes in the Web app resource paths:
/WEB-INF/lib
/WEB-INF/classes
Apr 08, 2013 4:26:28 PM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
class CatService
Apr 08, 2013 4:26:28 PM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Provider classes found:
class org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider
class org.codehaus.jackson.jaxrs.JsonMappingExceptionMapper
class org.codehaus.jackson.jaxrs.JsonParseExceptionMapper
class org.codehaus.jackson.jaxrs.JacksonJsonProvider
Apr 08, 2013 4:26:28 PM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.17.1 02/28/2013 12:47 PM'
Jersey automatically picked up your service and also discovered a JSON provider, that will help us convert objects to JSON . Try it yourself and call http://localhost:8080/RestTest/rest/cats in your browser. You should get the following:
[{"name":"Julien","age":2},{"name":"Tom","age":6}]