How to Build a RESTful Web Service with JAX-WS and Jersey on Eclipse

In order to build a RESTful API with Jersey on Eclipse, please use the following steps:

Create new Eclipse Dynamic Web Project

Open Eclipse, then File -> New -> Dynamic Web Project.
Name it “TestProject”.

Eclipse Dynamic Web Project

Eclipse Dynamic Web Project

Generating web.xml file

Generate a web.xml file IN WebContent/WEB_INF by:
Right click on the created project -> Java EE Tools -> Generate Deployment Descriptor Stub

How to generate wex.xml file

How to generate wex.xml file

Copy the following into the web.xml file

<!--?xml version="1.0" encoding="UTF-8"?-->
 
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>TestProject</display-name>
  <servlet>
    <servlet-name>Jersey Web Application</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>Jersey Web Application</servlet-name>
    <url-pattern>/api/*</url-pattern>
  </servlet-mapping>
</web-app>

Download Jar files

Download the following three jar files and put them under WebContents\WEB-INF\lib folder.

      asm-3.3.1.jar
      jersey-bundle-1.14.jar
      json.jar

lib

Create Java Class file

Create java class file with name DefaultResource and with package com.company.myserver.resources

Java Class

Java Class

Put the following code in the new created class:

package com.company.myserver.resources;
 
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.Produces;
 
@Path("/")
@Produces( {  MediaType.APPLICATION_XML } )
public class DefaultResource {
 
	@GET
	public String get() {
        return
        "<!--?xml version=\"1.0\" encoding=\"UTF-8\"?-->" +
        "" +
        	"Ilan Hazan" +
        	"Hello World" +
        "";
    }
}

Run as Server

Right click on the created project -> run as -> server

Run On Server

Run On Server

RunOnServer2
Neme: Apache Tomcat v7.0
Instalation directory -> create new directory
Click download and install for apache-tomcat-7.0.12
Please wait several minutes and then finish.
runOnServer3

Start the Server

In the server view you will see server instance. Right click -> clean. Then right click -> start.
Browse to: http://localhost:8080/TestProject/api
browser

Leave a Reply

*