REST Jersey Maven Tutorial

REST Jersey Maven Tutorial will drive you about REST application using JAX-RS where Jersey is implementation provider. Go through REST Concepts Tutorial before going through this tutorial. Download the REST Webservices at end of the tutorial.

Installations:

  • Jersey version : 1.19.3
  • Maven 4
  • Jackson :1.9.10

Maven REST Project:

  • In Eclipse, click on File -> New -> Maven Project  and select simple project  -> Click on NextNew Maven REST Jersey Project
  • Provide the below artifact config REST Jersey Maven Tutorial
  • Update the pom.xml with below  pom.xml
    • <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <groupId>org.javasavvy.jersey.rest</groupId>
       <artifactId>jersey-rest-tutorial</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <packaging>war</packaging>
       <build>
             <finalName>jersey-rest-tutorial</finalName>
             <directory>target</directory>
             <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
             <outputDirectory>target/classes</outputDirectory>
             <resources>
                 <resource>
                      <directory>${project.basedir}/src/main/resources</directory>
                      <filtering>false</filtering>
                 </resource>
             </resources>
       </build>
       <repositories>
           <repository>
              <id>maven2</id>
              <url>http://repo1.maven.org/maven2/</url>
           </repository>
       </repositories>
       <dependencies>
           <dependency>
              <groupId>com.sun.jersey</groupId>
              <artifactId>jersey-bundle</artifactId>
              <version>1.19.3</version>
             </dependency>
          <dependency>
             <groupId>org.codehaus.jackson</groupId>
             <artifactId>jackson-mapper-asl</artifactId>
             <version>1.9.10</version>
          </dependency>
         <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.10</version>
         </dependency>
         <dependency>
           <groupId>org.codehaus.jackson</groupId>
           <artifactId>jackson-xc</artifactId>
           <version>1.9.10</version>
         </dependency>
        <dependency>
           <groupId>org.codehaus.jackson</groupId>
           <artifactId>jackson-jaxrs</artifactId>
           <version>1.9.10</version>
         </dependency>
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.1.0</version>
         <scope>provided</scope>
        </dependency>
       </dependencies>
      </project>
  •  In this step, we will create REST Services that will be accessible and below configurations are required
    • A REST Resource class that annotated with @Path
    • Jersey REST servlet(com.sun.jersey.spi.container.servlet.ServletContainer)  mapping in web.xml  which  used to deploy REST Resources which are passed as init parameters.
      • “com.sun.jersey.config.property.resourceConfigClass” or “javax.ws.rs.Application” are passed as initialization parameter.In this case, you need to provide all REST resource to MAP
        •  <init-param>
           <param-name>javax.ws.rs.Application</param-name>
           <param-value>org.javasavvy.rest.CustomApplication</param-value>
           </init-param>
      • if above parameter is not set and “com.sun.jersey.config.property.packages” is passed as a initialization parameter and list of packages are need to passed as a value that separated by ‘;’
        •  <init-param>
           <param-name>com.sun.jersey.config.property.packages</param-name>
           <param-value>org.javasavvy.rest;org.javasavvy.mobile.rest</param-value>
           </init-param>
      • if none is present then it may throw  the exception “com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.”
    • A REST POJO that annotated with @XMLRoot Element for  marshalling/unmarshalling, but this is optional.
  • create web.xml file and add the below jersey servlet configuration
    •  <servlet>
           <servlet-name>jersey-rest</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.javasavvy.rest</param-value>
           </init-param>
          <init-param>
             <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
             <param-value>true</param-value>
            </init-param>
          <load-on-startup>1</load-on-startup>
       </servlet>
      
       <servlet-mapping>
          <servlet-name>jersey-rest</servlet-name>
           <url-pattern>/rest/*</url-pattern>
       </servlet-mapping>
    • com.sun.jersey.config.property.packages init parameter will scan the package for REST resources and creates them
    • com.sun.jersey.api.json.POJOMappingFeature will enable auto marshalling/unmarshalling of POJO’s to JSON/XML
  • Create a REST Resource controller. Let’s create sample controller
    1. @Path("/user")
      public class UserController {
       
       @GET
       @Path("/user-info/{userId}")
       @Produces(value={MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
       public UserModal getUserInfo(@PathParam("userId") long userId){
       
       UserModal userModal = new UserModal();
       userModal.setEmail("javasavvy@gmail.com");
       userModal.setAge(10);
       userModal.setFirstName("jayaram");
       userModal.setLastName("vijay");
       return userModal;
       }
       @GET
       @Path("/list")
       @Produces(value={MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
       public ArrayList<UserModal> getUsersList(){
       ArrayList<UserModal> list = new ArrayList<UserModal>();
       UserModal userModal = new UserModal();
       userModal.setEmail("rest-hellow@gmail.com");
       userModal.setAge(10);
       userModal.setFirstName("rest example");
       userModal.setLastName("jersey");
       list.add(userModal);
       
       UserModal userModal1 = new UserModal();
       userModal1.setEmail("jayaram3@gmail.com");
       userModal1.setAge(21);
       userModal1.setFirstName("test2");
       userModal1.setLastName("vijay");
       list.add(userModal1);
       return list;
       }
       
      }

 

Now run the Maven Install(make sure that you run everytime this if your changes are not reflected) and  deploy the changes into tomcat and download REST client in the chrome. (Right click on the project and select Run as Server to deploy into tomcat)

Result: Now hit the url with:

URL :   http://localhost:8080/jersey-rest-tutorial/rest/user/list

 

 

if you got the below exceptions:

  1. If you get the below Exception: java.lang.ClassNotFoundException: com.sun.xml.bind.v2.model.annotation.AnnotationReader then it
    • Exception:
    • java.lang.ClassNotFoundException: com.sun.xml.bind.v2.model.annotation.AnnotationReader
       at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1284)
       at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1132)
       at java.lang.ClassLoader.defineClass1(Native Method)
       at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
       at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
       at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2401)
       at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:871)
       at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1254)
       at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1132)
       at java.lang.Class.getDeclaredMethods0(Native Method)
       at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
       at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
       at java.lang.Class.getMethod0(Class.java:3018)
       at java.lang.Class.getMethod(Class.java:1784)
       at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:169)
       at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:131)
       at javax.xml.bind.ContextFinder.find(ContextFinder.java:335)
    • Solution: if you are using JAX-B for Jersey then make sure below all dependencies are added in the  pom.xml file as annotations are moved to jaxb-core.
      • <dependency>
         <groupId>javax.xml.bind</groupId>
         <artifactId>jaxb-api</artifactId>
         <version>2.2.12</version>
         </dependency>
         <dependency>
         <groupId>com.sun.xml.bind</groupId>
         <artifactId>jaxb-core</artifactId>
         <version>2.2.11</version>
         </dependency>
         <dependency>
         <groupId>com.sun.xml.bind</groupId>
         <artifactId>jaxb-impl</artifactId>
         <version>2.2.11</version>
         </dependency>
    • Clean maven and re run maven install again.

If you get the exception “com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.” then check the below to fix the issue:

  • Exception :
  1. com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
     at com.sun.jersey.server.impl.application.RootResourceUriRules.<init>(RootResourceUriRules.java:99)
     at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1359)
     at com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:180)
     at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:799)
     at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:795)
     at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
     at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
     at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
     at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:509)
     at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:339)
     at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
     at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
     at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:394)
     at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:577)
     at javax.servlet.GenericServlet.init(GenericServlet.java:158)
     at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1236)
     at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1149)
     at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1041)
     at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4906)
     at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5188)
     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1387)
     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
     at java.lang.Thread.run(Thread.java:745)
    • Solution:
      • set scan package to in Jersey servlet
        • <init-param>
          <param-name>com.sun.jersey.config.property.packages</param-name>
          <param-value>{your rest package path}</param-value>
          </init-param>
      • Check the Controller may have missed @PATH configuration
      • Right click on project, remove all external dependencies and then set the build path to latest JAVA and Maven dependencies

 

Download REST Jersey Maven Code

1 Comment

  1. Pingback: Jersey Spring integration,Jersey + Spring Tutorial,Jersey spring 4 maven

Leave a Comment

Your email address will not be published. Required fields are marked *