RESTful WS using Jersey: "Hello world!"

JAX-RS is a java specification which define APIs to implement RESTful web services. Jersey is a reference implementation of JAX-RS. It provides libraries to develop RESTful web services based on the JAX-RS specification. It uses a servlet to receive and dispatch client requests to right execution classes. In this tutorial, we will develop a simple service which returns string “Hello world!” to client using Jersey.


Step 1: setting up Tomcat on Eclipse

Step 2: Create your project

  1. Open Eclipse, File→New→Dynamic Web Project.
  2. Name the project: rest. Select Target runtime as your Apache Tomcat. Click Finish.
  3. Download and extract the Jersey package.
  4. Copy jersey-server.jar , jersey-core.jar, jersey-servlet.jar and asm.jar to the WebContent→WEB-INF→lib folder.
  5. Create new package in the src folder. Name it:
  6. Create new Java class inside this package. Name it: Hello.
  7. Edit it as following:

    public class Hello {
      // This method is called if TEXT_PLAIN is requested
      public String sayHelloInPlainText() {		  
        return "Hello world!";
      // This method is called if HTML is requested
      public String sayHelloInHtml() {
        return "<html> " + "<title>" + "Hello world!" + "</title>"
            + "<body><h1>" + "Hello world!" + "</body></h1>" + "</html> ";

Step 3: Define the servlet container

  1. Create a file: web.xml in the WebContent→WEB-INF folder.
  2. Insert the following code into the web.xml file:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="" xmlns="" 
    id="WebApp_ID" version="3.0">
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-name>Jersey REST Service</servlet-name>
  • Note that:
    1. <param-value> is your package's name.
    2. the URL of your service will be: http://your_domain:port/<project-name>/<url-pattern>/<path_from_rest_class>. In this example, this URL is: http://localhost:8080/rest/hello (<project-name> is rest, <url-pattern> is empty, <path_from_rest_class> is hello as declared in step 2).

Step 4: Publish and check your service

  1. Start the Tomcat server
  2. Right click on Tomcat server→Add and Remove…. Select the rest project.
  3. Verify the response in HTML by your browser: http://localhost:8080/rest/hello.
  4. Verify the response in PLAINTEXT using command curl: open your terminal and type: curl http://localhost:8080/rest/hello
teaching_assistant/web_services/jersey_helloworld.txt · Last modified: 2013/01/15 15:13 by Nguyen Ngoc Chan
Back to top
CC Attribution-Noncommercial-Share Alike 3.0 Unported = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0