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: 

You can find a basic tutorial about jQuery Ajax here.

Regards
Rafael Sobek

Technorati Tags:

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

 

[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.

Comment: darren at Do, 7 Okt 5:29 AM

Nice example but you have a ton of errors in this from not instantiating your classes to declaring multiple element Id's with the same name in your HTML

Comment: Dan at Di, 20 Sep 9:51 PM

@Darren, you need to learn spring before you comment on what Rafael wrote...

DI is a cool technology, unfortunately not everyone understands it well enough, you could just search on spring and learn DI :)

Comment: Wes at So, 25 Sep 7:46 PM

How do you user a complex type for the input of a get request?

Say, you wanted to make your method like this:

public SumRestResult sum(SumRequest sr) { ...}

Is that possible? Not sure how it would interact with the query params or if you posted a data object from the jquery .ajax method post data { firstNumber: 1, secondNumber:2 } .

Any info would be great.

Wes

Comment: Renan at Sa, 12 Nov 5:03 AM

Do you code source this application example?
I could not create this application, please help me.

Thanks you.

Comment: Burnaby at Mi, 8 Feb 4:07 AM

Can anybody share the complete downloadable code? few things I couldn't understand how to put them together. I am using Eclipse. appreciate the help.

Comment: Syzygy at So, 12 Feb 2:44 AM

Do you have downloadable code or project interchange. I am using eclipse. I can't put everything together working. Thanks for help.

Comment: A at Di, 14 Feb 11:51 AM

Can you place the source code to download?

Comment: Mariana at Mo, 12 Mrz 12:58 AM

Morten sagt:Hi. I am trying to use your sttrus2-jquery-plugin. However, I have some problems. This is the scenario. I have a huge form, this form contains a login dialogue. I want this login dialogue to open in a DialogTag (this is working). The Dialog contains the submit button which I want to use for posting the main form. I have tried using the SubmitTag, but this only submits the input values in the main form, not the input values in the login dialog.Do you have any thoughts about this? don't hesitate to contact me by email and I can provide code samples as well.

Comment: lalit at Mi, 30 Mai 1:43 PM

thanks can you put a example for jquery post also,where a form can be submitted to jersey method without using FormParam instead using JAXBElement

Comment: women air jordan at Sa, 27 Apr 12:44 AM

JQuery Ajax Client and Jersey Rest Endpoint Example

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
 
test