Newsletter

Jersey Hello World Example Using JAX-RS Specification

Web Services » on Jul 6, 2014 { 37 Comments } By Sivateja

In this tutorial, I will show you how to develop a RESTful hello world web application with Jersey & Maven in Eclipse.  I have used Eclipse Juno to develop all web services. Make sure you have installed Maven plugin in eclipse before you start, you can check this article for help [ How to Install m2eclipse (Maven) Plugin in Eclipse ]

Required

  • Eclipse Juno
  • JDK 1.6
  • Jersey 1.8
  • Maven Plugin
  • Tomcat 6.0 Server

Steps

  • Create a ‘Dynamic Web Project’
  • Convert the project into ‘Maven Project’ [ Of course you can also create Maven project directly ]
  • Add required dependencies in ‘pom.xml
  • Change web.xml [ register com.sun.jersey.spi.container.servlet.ServletContainer and add related init-param]
  • Run the application

Steps to Create Restful Web Services in Eclipse

Open Eclipse > File > New > Dynamic Web Project

Give the project name and choose ‘Dynamic web module version’ as 2.5 > Finish

Now the project will be created in the work space, right click on the project folder > Configure > Convert to Maven Project

Now it will open Maven POM window, there keep everything as it is, but choose packaging to .war and click Finish

You have created a Maven project, finally your project looks like..

Most probably it will not show any errors, but here Its showing errors. In order to fix this right click on the project > Maven > Update Project > Now you can see the errors gone 🙂

Open pom.xml and add the Maven dependencies just like bellow

Pom.xml

What is pom.xml :
It is an XML file that contains information about the project and configuration details used by Maven to build the project.  Generally at the time of developing any J2EE applications we will search and download the related jar files over the internet and we need to add them in the class path and even in the lib folder as well. But if you can install Maven plugin in your Eclipse, pom.xml will take care of adding these dependencies (‘*.jars) to the project. Your work is to install Maven and  update pom.xml with the required dependencies (jars). However i have already explained, how to install Maven plugin in the Eclipse.

<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>RestPathAnnotationExample</groupId>
<artifactId>RestPathAnnotationExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<repositories>
       <repository>
         <id>maven2-repository.java.net</id>
          <name>Java.net Repository for Maven</name>
          <url>http://download.java.net/maven/2/</url>
          <layout>default</layout>
       </repository>
</repositories>

<dependencies>
       <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.8.2</version>
          <scope>test</scope>
       </dependency>

       <dependency>
          <groupId>com.sun.jersey</groupId>
          <artifactId>jersey-server</artifactId>
          <version>1.8</version>
       </dependency>
</dependencies>

<build>
   <finalName>RestPathAnnotationExample</finalName>
   <plugins>
      <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
             <configuration>
                <compilerVersion>1.5</compilerVersion>
                <source>1.5</source>
                <target>1.5</target>
             </configuration>
       </plugin>
   </plugins>
</build>

</project>

Once you add dependencies [ required libraries ] in pom.xml  > right click on the project > Maven > Update Project > Choose the current project > Ok

HelloWorldService.java

package com.java4s;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@Path("/customers")
public class HelloWorldService {

  @GET
  @Produces("text/html")
  public Response getLocalCust() {

           String output = "I am from 'getLocalCust' method";
           return Response.status(200).entity(output).build();
  }

  @GET
  @Path("/nri")
  @Produces("text/html")
  public Response getNriCust() {

            String output = "I am from 'getNriCust' method";
            return Response.status(200).entity(output).build();
  }
}

web.xml

<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>RestPathAnnotationExample</display-name>

<servlet>
    <servlet-name>jersey-serlvet</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>com.java4s</param-value>
       </init-param>
       <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
   <servlet-name>jersey-serlvet</servlet-name>
   <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

</web-app>

<!-- www.Java4s.com -->

Now we are good to run the application, Just right click on the project >Run As > Run on Server > It will open the application URL like
http://localhost:2013/RestPathAnnotationExample/ 

But you need to satisfy the actual URL pattern, i mean change the URL to…

Main application URL:
http://localhost:2013/RestPathAnnotationExample/

Web.xml URL pattern:
/rest

@Path in HelloWorldService.java:
/customers

Final URL should be
http://localhost:2013/RestPathAnnotationExample/rest/customers

Hit with this final URL in your web browser or eclipse browser

It will throw 404 error, because we forgot to add the Maven dependencies in the Deployment Assembly. So how to fix this issue ? just right click on the project > Properties > Deployment Assembly > Add > It will open other window, in that choose ‘Java Build Path Entries‘ click Next..

Choose the Maven Dependencies root and Finish

Now it looks like..

Click Ok > and test the application with URLs
http://localhost:2013/RestPathAnnotationExample/rest/customers

http://localhost:2013/RestPathAnnotationExample/rest/customers/nri  [ Here /nri  is the path i have mentioned in HelloWorldService.java  for getNriCust() method]

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

37 Responses to “Jersey Hello World Example Using JAX-RS Specification”
  1. Siva says:

    Can you please provide one JAX-RS web service example with out annotations. Actually i am learning Web services.

  2. good exaple. never thought that web services are so simple 🙂

  3. Swati says:

    Hi Sivateja , thank you very much for such a simple and helpful sample code…

  4. Dishari says:

    I got this exception after following your every step:

    javax.servlet.ServletException: Servlet.init() for servlet jersey-serlvet threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Unknown Source)

    root cause

    com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
    com.sun.jersey.server.impl.application.RootResourceUriRules.(RootResourceUriRules.java:99)
    com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1298)
    com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:169)
    com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:775)
    com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:771)
    com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
    com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:771)
    com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:766)
    com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:488)
    com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:318)
    com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:609)
    com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
    com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:373)
    com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:556)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Unknown Source)

    • Rahul says:

      you need to cheak your package name in web.xml then you will not get any error…..

    • Kantheti Manoj Sanjay says:

      Modify Change @Path("/customers") to @Path("customers") in class level path Annotation. Then the issue will be resolved.

    • G Praveen says:

      I am also getting the same issue.Please help me to get resolved.

      Thanks in advance

      • satya says:

        Check the package name which you specified in web.xml. like "com.java4s". it should be your service package name whatever you specified in your code base.
        <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.java4s</param-value>
        </init-param>

  5. Remya says:

    very good presentation

  6. Mohan says:

    Excellent buddy

  7. Honeybee says:

    Goodone

  8. om says:

    Hi,

    i am beginner in web services . when i deploye your code then i got http 404 error “HTTP Status 404 – /RestPathAnnotationExample/rest/customers”. please help me.

  9. sandhya says:

    Hi SivaTeja,

    In My project i am using resful webservices.

    We are able integrate for the PUT request. But when we are doing DELETE towards Xxxx we are getting below exception.

    Please help.

    HTTP method DELETE doesn’t support output
    java.net.ProtocolException: HTTP method DELETE doesn’t support output
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
    at ilink..Connection.ipActivateService(Connection.java:109)
    at com.IPServiceManagement.ipActivateService(IPServiceManagement.java:44)
    at com.IPServiceManagement.execute(IPServiceManagement.java:30)
    at macro_NMSIP_IPSERVICEMNGNT_V1.create(macro_NMSIP_IPSERVICEMNGNT_V1.java:117)
    at com.java_macroserver.MacroServer.executeTask(Unknown Source)
    at com.java_macroserver.MacroServer.handleRun(Unknown Source)
    at com.java_macroserver.MacroServer.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

  10. sanjeev says:

    Hi, thanks a lot.
    for this nice example. But for last few of months we are not able to see any new tutorial.

  11. naveen says:

    After updating the maven project, where to create HelloWorldService.java ?.
    Please explain, newbie here. reply asap

  12. devi says:

    Hi I follow this steps but i got error

  13. Paridhi says:

    Thankyou so much! Your post was very clear and descriptive which helped me to do my job quickly!Keep posting!

  14. Rupesh says:

    @Dishar,
    Its unable to find your class. Please check package name in web.xml file and form action path in client.html.

  15. Rupesh says:

    Hi Siva,
    Thanks for such ultra simple and easy to understand tutorial. Can you please explain, what happens when we update maven project?

  16. Mekha says:

    Thank you so much for this great tutorial. It is definitely a good start 🙂

  17. Himanshu says:

    Man, you have done awesome work by publishing this step by step tutorial. You ROCK!!!!!

  18. trineesha says:

    Thanku so much

  19. manoj says:

    Thanks Siva

  20. venkat says:

    Very good article

  21. Sandeep says:

    pls provide info regarding tools also..

  22. piyush k says:

    Hi siva,

    Please provide me one JAX-RS web service example with out annotations.

  23. amol says:

    hi, best example
    please explain that
    in web.xml
    about com.java4s

  24. dhiraj says:

    Easy and straight forward steps. Really helpful.

  25. Anil Kumar says:

    When I am running this program I am getting my webpage open via 8080 port and giving error it is already in use by another process. How can I change it to other port.

  26. Anil Kumar says:

    After following all the steps. At the end page giving 404 error as shown in page already and after applying its given fixed same error is coming.

  27. Aasif says:

    The service class "com.java4s.HelloWorldService" does not comply to one or more requirements of the JAX-RPC 1.1 specification, and may not deploy or function correctly.

  28. Pawan Bhardwaj says:

    This tutorial is excellent for beginners… thanq sir

  29. Shanu says:

    This tutorial is excellent…could you provide some details on Postman Application as how we need to test our Web-Service on postman with jersey client…..thanks waiting for your update on Postman.:)

  30. arun singh says:

    Thanks, very helpful brother

  31. sanju says:

    What is the difference between web.xml and pom.xml ?

  32. Prabhakar Ranjan says:

    web.xml is to configure web components present in web-container, whereas pom.xml is to configure dependencies in Maven.

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.