Jersey GWT on Tomcat in Eclipse

This tutorial will show how to use Eclipse to build GWT projects that uses JAX-RS Jersey to make server side call on a Tomcat platform. Instead to describing things I’ll let code and screen shot do the talking.

Environment

  • Sandbox OS: Windows 7 32 Bit
  • IDE : Eclipse Indigo
  • Libraries:
    • JAX-RS Jersey
  • Web Container: Tomcat 6
  • Client Technology: Google GWT 2.4

Create Web Project

Create a Dynamic Web Project using Eclipse Indigo

clip_image001

Enable Jersey

  • Download Jersey 1.10 from here http://jersey.java.net/ . You should download a “zip of Jersey” to your local folder.
  • Explode the archive and copy all jar from lib folder and place them in your Eclipse project under /WEB-INF/lib folder
  • Add these jar files by going to Project properties->Java Build Path -> Add Jars

clip_image002

Create a Jersey annotated resource class “EmployeeResource.java”. This is your JAX-RS Jersey enabled REST class.


EmployeeResource

@Path("/employees")
public class EmployeeResource {

	Logger logger = Logger.getLogger(EmployeeResource.class.getName());

	private static final long serialVersionUID = 1L;
	private final Map<String,String> employees = new TreeMap<String,String>();

	public EmployeeResource(){
		employees.put("001", "John Doe");
		employees.put("002", "Modon Tak");
		employees.put("003", "Cat Stephen");
		employees.put("004", "Alimu Jaingar");
	}

	@GET
	@Produces("text/plain")
    public Response getHelloWorld() {
		ResponseBuilder rb = Response.ok("Hello World !");
		return rb.build();
	}

	@GET
	@Path("/{employeeid}/")
	@Produces("text/plain")
    public Response getEmployee(@PathParam("employeeid") String employeeid) {
		if(employees.containsKey(employeeid)){
			String employeeName = employees.get(employeeid);
			ResponseBuilder rb = Response.ok("Hello : " + employeeName);
			return rb.build();
		}else{
			ResponseBuilder rb = Response.ok("Could not find employee with id : " + employeeid);
			return rb.build();
		}
	}

	@PUT
	public StreamSource putTest(StreamSource streamSource){
		if(streamSource != null){
			logger.info(streamSource.toString());
			return streamSource;
		}else {
			return null;
		}

	}

}

web.xml

Add following parameters to web.xml file to enable servlet container to find Jersey annotated resource file. The container will look for Jersey resources under com.dcl.gwtjersey as per the web.xml.

<?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_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>WP_JerseyGWTTomcat</display-name>

	<servlet>
		<servlet-name>jersey</servlet-name>
		<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
		<init-param>
			<param-name>com.sun.jersey.config.property.resourceConfigClass</param-name>
			<param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value>
		</init-param>
		<init-param>
			<param-name>com.sun.jersey.config.property.packages</param-name>
			<param-value>com.dcl.gwtjersey</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>jersey</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>GWTJersey.html</welcome-file>
	</welcome-file-list>

</web-app>

Add Tomcat Server

  • Follow steps below If you don’t have Tomcat server configured with Eclipse.
  • You must have a Tomcat already in your PC in
  • In Eclipse go to Window -> Show View -> Other… -> Server -> Servers and you will be presented with a Server view.
  • Right click and select New –> Server

clip_image003

  • Click next to get “New Server” window. Click “Browse” button and locate your Tomcat root. Click “Finish” button.

clip_image004

  • On “Server” view you should see an entry for your Tomcat server. Right click on Tomcat server and select “Add and Remove..” button”. Then select your project from “Available” project on the left and “Add” the project to “Configured” projects bucket on the right. Click “Finish”

clip_image005

Test Jersey Integration

  • Now test if Jersey got integrated properly using a Web Browser.
  • Start Tomcat from “Server” view
  • Open your browser and type up the following url and you should receive a “Hello World !” typed up in your browser window.
    • http://localhost:8080/WP_JerseyGWTTomcat/rest/employees/
      • Where localhost:8080 is your tomcat root
      • Where WP_JerseyGWTTomcat is your Web project name.
      • /rest is defined in web.xml as url pattern to your rest resources.
      • /employees is defined in your Jersey Resource class EmployeeResource.java

So we have Jersey setup in our project and now it is time to integrate Google GWT.

Enable GWT

  • This tutorial assumes Google Eclipse Plugin is already installed on to your Eclipse IDE.
  • On Eclipse open up project “properties” window.
  • Select Google –> Web Toolkit. Check “Use Google Web Toolkit” to enable GWT.

clip_image006

  • Select Google –> Web Application and check “This project has a WAR directory and make sure that “WebContent” is selected as “WAR Directory”.
  • Click “OK”.

clip_image007

  • Eclipse is enabled now to build GWT Artifacts. Let us build some GWT artifacts.
  • Create GWT Module and name it “GwtJerseyModule”

clip_image008

  • Here is the content of the module

GwtJerseyModule

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.4.0//EN" "http://google-web-toolkit.googlecode.com/svn/tags/2.4.0/distro-source/core/src/gwt-module.dtd">
<module rename-to='gwtjersey'>
	<inherits name="com.google.gwt.user.User" />
	<source path="client" />
	<entry-point class="com.dcl.gwtjersey.client.GwtJerseyEntryPoint"></entry-point>
</module>

Create entry point class and name it “GwtJerseyEntryPoint”. Use “GwtJerseyModule” as it’s module.

clip_image009

  • Add code to entry point class as bellow.

GwtJerseyEntryPoint

public class GwtJerseyEntryPoint implements EntryPoint {

	Label label = new Label("Enter Employee Id like 001, 002, 003 or 004 : ");
	final TextBox textBox = new TextBox();
	Label result = new Label("");
	Button button = new Button("GET something RESTfully");

	@Override
	public void onModuleLoad() {
		button.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				Window.alert("You entered: " + textBox.getText());
				getHello(textBox.getText());
			}
		});

		RootPanel.get("basicseat").add(label);
		RootPanel.get("basicseat").add(textBox);
		RootPanel.get("basicseat").add(button);
		RootPanel.get("basicseat").add(result);
	}
}

Add host HTML page named GWTJersey.html and add the following line in the page.


GWTJersey.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Simple MVP</title>
<link type="text/css" rel="stylesheet" href="GWTJersey.css">
<script type="text/javascript" language="javascript" src="gwtjersey/gwtjersey.nocache.js"></script>
</head>
<body>
	<div id="uibinderseat"></div>
	<div id="basicseat"></div>
</body>
</html>

Do “GWT Compile”

clip_image010

When prompted for compile artifact location choose “WebContent” to save your compiled GWT artifacts.

clip_image011

Compilation would succeed after a while.

clip_image012

A folder named “gwtjersey” should show up under WebContent folder which will contain all your compiled GWT artifacts.

Test GWT Integration

  • Let us test GWT Integration now.
  • Start Tomcat from “Server” view
  • Open your browser and type up the following url and you should receive a “Hello World !” typed up in your browser window.
  • You should see a Label text and a button on your browser window.
  • This step will conclude that GWT was integrated with Tomcat fine. Now we will need to make a REST call using GWT client.

GWT calling Jersey REST Resource

How do we call REST resources using GWT? We are going to use com.google.gwt.http.client.RequestBuilder object to make Asynchronous call to EmployeeResource resource. After adding RequestBuilder specific java code to GwtJerseyEntryPoint.java the full class will look like bellow.

</span>
<pre>public class GwtJerseyEntryPoint implements EntryPoint {

	Label label = new Label("Enter Employee Id like 001, 002, 003 or 004 : ");
	final TextBox textBox = new TextBox();
	Label result = new Label("");
	Button button = new Button("GET something RESTfully");

	@Override
	public void onModuleLoad() {

//		HelloJerseyUiBinder binder = new HelloJerseyUiBinder("dipu");
//		RootPanel.get("uibinderseat").add(binder);

		button.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				Window.alert("You entered: " + textBox.getText());
				getHello(textBox.getText());
			}
		});

		RootPanel.get("basicseat").add(label);
		RootPanel.get("basicseat").add(textBox);
		RootPanel.get("basicseat").add(button);
		RootPanel.get("basicseat").add(result);
	}

	private void getHello(String employeeId) {

		String url = "rest/employees/"+employeeId;

		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL
				.encode(url));
		builder.setCallback(callbackHandler);
		try {
			Request request = builder.send();
		} catch (RequestException e) {
			GWT.log("RequestException ", e);
		}

	}

	RequestCallback callbackHandler = new RequestCallback() {

		public void onError(Request request, Throwable exception) {
			GWT.log("Error", exception);
		}

		public void onResponseReceived(Request request, Response response) {

			String responsetext = response.getText();
			Window.alert(responsetext);
			result.setText(responsetext);
		}
	};

}

Notice getHello and callbackHandler method. getHello() method is using url pattern ‘rest/employees/{employee id}’ to call server side REST resource utilizing RequestBuilder object. We are using callbackHandler() method to receive result from server side in asynchronous nature. If the call was successful we would print the result using “result” gwt Label widget.

Conclusion:

Hope this tutorial helps people who just want to use Eclipse to build GWT with Jersey with Tomcat server.

Resources:

Comments

  1. This is excellent and a much needed resource!! Many thanks!

  2. gatapolaga says:

    Hi, many thanks for the tutorial. however when i tried to type ur code in eclipse it gives a compile time error in below line

    ResponseBuilder rb = Response.ok(“Hello World !”);

    Response.ok—>

  3. jrgdre says:

    Hi, thank you for the helpful post!

    I use Eclipse Kepler, Apache 7.0, GWT 2.5.1 and jdk1.7.0.

    When compiling GWT, I experienced stack overflows. This was solved by moving GWT to the top of the Java Build Path.

    To be able to access GWTJersey.html after starting the server I needed to create an GWTJersey.css and add “rename-to=’gwtjersey'” to the tag in gwtJerseyModule.gwt.xlm

    • Asish says:

      Hi Jrgdre,
      I am facing “Stack Overflow” error too… i tried to put GWT at the top of the build path but the error is still there…
      could you help me?

Leave a Reply