April 27, 2010

JQuery Ajax Client and Jersey Rest Endpoint Example

« Auto Deployment of OSGI Bundles with Felix File Install | Main | SoapUI : JDBC Request Step example with a Sybase database »

JQuery is a JavaScript framework for DOM manipulation and navigation. Jersey is the reference implementation of the Java API for RESTful Web Services (JAX-RS).

Furthermore JQuery can be used to realize AJAX based browser clients. On the other hand Jersey is useful to implement server-side RESTful webservices, that handles the JSON format.

The best way to understand something new is to make an easy example. The following example contains a Spring based Jersey REST endpoint, that generates JSON data. This endpoint expects two numbers, which will be summed up. You can enter this two numbers on web page. JQuery code will get the data from the REST endpoint and will append the result to the DOM. By clicking a refresh button the data will be refreshed.

(1) First I created a Maven "webapp" project with the following command.

mvn archetype:create -DgroupId=org.developers.blog.examples -DartifactId=ajax-rest-jason-webapp -DarchetypeArtifactId=maven-archetype-webapp

(2) Second I downloaded the JQuery JavaScript API from here. I saved the downloaded file in src/main/webapp/scripts/ directory of my webapp.

(3) After that I added the following dependencies and repositories to the pom.xml file.

    ...
    
        com.sun.jersey
        jersey-server
        1.0.3
    
    
        com.sun.jersey
        jersey-json
        1.0.1
    
    
        com.sun.jersey.contribs
        jersey-spring
        1.0.1
    
    
        com.sun.xml.bind
        jaxb-impl
        2.1.9
    
    
        javax.ws.rs
        jsr311-api
        1.0
    
    
        org.springframework
        spring
        2.5.6
    
    ...
    
      
        java.net
        http://download.java.net/maven/2
      
    
    ...
    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                2.0.2
                
                    1.5
                    1.5
                
            
            
                org.mortbay.jetty
                maven-jetty-plugin
                6.1.9
            
        
    

(4) Next I created a MathService, that calculates the sum of two numbers.

public class MathService {
    public int sum(int firstNumber, int secondNumber) {
        return firstNumber + secondNumber;
    }
}

(5) JAXB based class for the REST response.

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class SumRestResult {
    private Integer firstNumber;

    private Integer secondNumber;

    public Integer getFirstNumber() {
        return firstNumber;
    }

    public void setFirstNumber(Integer firstNumber) {
        this.firstNumber = firstNumber;
    }

    public Integer getSecondNumber() {
        return secondNumber;
    }

    public void setSecondNumber(Integer secondNumber) {
        this.secondNumber = secondNumber;
    }

    private Integer total;

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }
}

(6) Jersey annotated business logic class. After a request the sum method will be called.

import com.sun.jersey.spi.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

@Path("/sum")
public class SumRestEndpoint {
    @Inject
    private MathService mathService;

    @GET
    @Produces("application/json")
    public SumRestResult sum(
            @QueryParam("firstNumber") String firstNumber,
            @QueryParam("secondNumber") String secondNumber) {
        SumRestResult result = new SumRestResult();
        result.setFirstNumber(Integer.parseInt(firstNumber));
        result.setSecondNumber(Integer.parseInt(secondNumber));
        result.setTotal(mathService.sum(Integer.parseInt(firstNumber), Integer.parseInt(secondNumber)));
        return result;
    }
}

(7) After that I set up the Spring application context file for dependency injection.



   

(8) Now you have to configure the Jersey Spring servlet.

   
      Jersey Spring Servlet
      com.sun.jersey.spi.spring.container.servlet.SpringServlet
      
        com.sun.jersey.config.property.resourceConfigClass
        com.sun.jersey.api.core.PackagesResourceConfig
      
      
        com.sun.jersey.config.property.packages
        org.developers.blog.ajaxrest.example
      
      
    
      Jersey Spring Servlet
      /services/*
    

(9) Now you can start your application with the command mvn jetty:run. If you call the address http://localhost:8080/ajax-rest-jason-webapp/services/sum?firstNumber=1&secondNumber=2 in your browser, you will get the following JSON data.

{"firstNumber":"1","secondNumber":"2","total":"3"}

(10) The following HTML file shows how to use JQuery Ajax calls for access REST JSON data.


    
        
        
    
    
        
Ajax based sum calculation:
FirstNumber:
SecondNumber:
Click here
Sum of and is: 

Regards
Rafael Sobek

Technorati Tags:

Posted by rafael.sobek at 9:27 PM in Uncategorized

 

[Trackback URL for this entry]

Comment: Peter at Do, 29 Apr 12:46 PM

nice tutorial (ignoring typos) ...

by the way instead of downloading the script (step 2), you could as well just import above mentioned url

<code><script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"> </script></code>

Comment: JP Singh at Mi, 19 Mai 12:58 AM

Nice one mate. Cheers

Comment: JP Singh at Mi, 19 Mai 1:02 AM

Nice one mate. Thanks for sharing.
Cheers

JP

Comment: Adi at Fr, 16 Jul 11:13 AM

Do you have downloadable code for this? If this is without Spring, that would be great.

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
« April »
SunMonTueWedThuFriSat
    123
45678910
11121314151617
18192021222324
252627282930