Tuesday, May 29, 2012

Implementing Jersey (JAX-RS) in to a GWT application

I want to build my GWT project using a Jersey (JAX-RS) backend to decouple the Client from the Server and to allow different kind of Clients (developed in all kind of languages) to connect to my application

This tutorial is based on Eclipse as it is the only client supported by GWT currently. I have read that there can be difficulties using Maven. Hence these instructions are following the manual (official) way how to add third party server side libraries.

Create a new GWTP Project
First thing you have to do is to create a new GWTP (GWT-Platform) project. Don't tick the creation of sample code.

Add Jersey (and dependent) Libraries
The following libraries have to be downloaded and added to the war/WEB-INF/lib directory:
It is important to take the same Versions for the jersey-core, jersey-server and jersey-json JARs. Otherwise you can get errors during execution.

Add Libraries to the Classpath
  • Right click on to the application in Eclipse
  • Choose Properties
  • Choose Java Build Path
  • Choose Libraries
  • Click on to Add Jar 
  • Select all the Jar files from above (jersey-core, jersey-server, jersey-json and asm)
  • Click Ok to add them to the build path

Create a new Resources Java Package
  • Right click on to the src folder within Eclipse
  • Choose New -> Package
  • Insert your Package name: com.yourcompany.yourapp.resources

Add necessary lines to web.xml
You need to add some lines to web.xml. You need to initialize some Jersey related stuff but what is especially important that you add the package path and the url-pattern.

When starting your GWT application in it's default configuration you should be able to execute a servlet over the path<Resource>.

        The below lines are implementing Jersey (JAX-RS) in to the GWT application.

Create a Hello Resource
Right click on to the package com.yourcompany.yourapp.resources
Choose New -> Class
Name your Class HelloResource.java

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

public class HelloResource {
    public String sayHello() {
        return "Hello Jersey";

Once finished you should be able to run the application as Webapplication.
Right click on to your application
Choose Run As -> Google Web Application

Please note that the default URL will not work as there haven't been any GWT Presenters implemented. But you should now be able to open following URL:

1 comment:

  1. This comment has been removed by the author.