Tomcat 7: REST services with Jersey

First download Apache Jersey. I downloaded the archive with the follow jars in them and placed them in /usr/share/tomcat7/lib and restarted tomcat.


I had to increase Tomcat's memory size to avoid out of memory errors. I put this line at the top of /usr/share/tomcat7/bin/


Then you can create a simple POJO with the @XMLRootElement annotation. This will allow it to be converted into JSON for the REST services (Yes, it does say XMLRoot...)

 public class JsonObject {
   private String str;
   public String getStr() {
      return str;
   public void setStr(String str) {
      this.str = str;

Next you can create your REST class by creating a class like the following:

 public class Rest {
   UriInfo info;
   Request request;
   ServletContext context;
   public void init() {

This defines a new rest api that will have the '/rest/' prefix. The @Context annotation injects UriInfo and details of the actual request that you may want to use. You can access these methods in a method annotated with @PostConstruct

The real logic comes in the method signatures:

 public String sayRest() {
   return "rest";

 public String sayRest() {
   return "html text";

This will produce different responses, depending on whether the client is asking for plain text or html. The path is /rest/r.

This produces and consumes the POJO object we created above:

 public JsonObject intakeJson(JsonObject intake) {
   intake.setStr("intaken: " + intake.getStr());
   return intake;

You can either pass in query parameters or path parameters:

 public String sayRestInHtml(@QueryParam("q") String q) {
   return "rest: "+q;
 public String sayRestInHtmlWithPath(@PathParam("q") String q) {
   return "rest with param: "+q;

You'd access these via /rest/r?q=sdfsdf and /rest/r/sdfsdf.

You can craft HTTP responses using:


This creates a CREATED HTTP response with the absolute path gained from the UriInfo via the @Context annotation above.

You now need to edit your web.xml to activate this servlet:

    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-name>Jersey REST Service</servlet-name>

This is a normal servlet mapping except the servlet-class is a Jersey class, and the init-param state where the REST class is. And the com.sun.jersey.api.json.POJOMappingFeature ensures you use Jackson instead of the standard Java implementation JaxB (which you don't want).

You final urls will be such as

java-jersey java java-servlet java-tomcat

Edit on github
comments powered by Disqus
Click me