7 de nov. de 2012

Build a RESTful webservice using Java, JSON and javascript

With JavaEE (6 or higher) and glassfish webserver, the RESTful development with any response data types is easy using simple annotations and Jersey.

Go to code and configuration steps:

1) Open the web.xml of your Dynamic web project and add a new servlet configuration:

<servlet>
      <servlet-name>my-service-name</servlet-name>
      <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
      <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.thesimplework.example.servicespackage</param-value>
      </init-param>
      <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>

 <servlet-mapping>
       <servlet-name>my-service-name</servlet-name>
      <url-pattern>/service-url-to-access/*</url-pattern>
  </servlet-mapping>

Notes:
    servlet-name: The name of your services.

    init param jersey packages: Location of your webservice classes, all services and annotations will be create at this location

2)  Implements a first RESTful webservice class:

package com.thesimplework.example.servicespackage;

import java.util.LinkedList;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Path("/simple-work-service-one") 
@RequestScoped
public class SimpleWorkServiceOne {
   
    @Inject
    SimpleWorkBusiness business;
   
// this service returns a list of cities from received country
// and return this list with JSON response

    @GET
    @Path("/find-cities")
    @Produces(MediaType.APPLICATION_JSON)
    public JSONObject getCities( @QueryParam("country") Integer countryId) {
        JSONArray array = new JSONArray();
        JSONObject joReturn = new JSONObject();
        try {
            List<City> cities= business.findCityByCountry(countryId);

            if (cities!=null) {
                for (City city: cities) {
                    JSONObject jo = new JSONObject();
                    jo.put("id", city.getId());
                    jo.put("name", city.getName());
                    jo.put("state", city.getState().getName());
                    jo.put("country", city.getCountry().getName());
                    array.add(jo);
                }
            }
            joReturn.put("array",array);
            joReturn.put("status",true);
         } catch (Exception e) {
             e.printStackTrace();
             joReturn.put("status",false);
         }
        return joReturn;
    }

3) Get the list of JSON objects using a simple javascript instruction:

<script type="text/javascript" language="javascript">

function loadAllCitiesOfBrazil() {

        var array= new Array();
         $.ajax({  
            type: "GET",
            cache: false, 
            url: "http://localhost/my_application//simple-work-service-one/find-cities?country=123",
            success: function(data){
                    if (data.status+"" == "true") {
                       array = data.array;
                    for(var  i = 0; i< array.length; i++) {
                        $("#my-select-html-object").append("<option value=\""+array[i].id+"\">"+array[i].name+"-"+array[i].state+"</option>");
                    }
                    }                       
            }  
        });
}
</script>

Note: Json is a js native response of our service and $("#id") is a reserved function from jquery.

4) If you execute a function loadAllCitiesOfBrazil(); a html select with id  "my-select-html-object" located on html (or jsp/jspx/php/asp/etc...) receive all values of our webservice.

spected result:

Nenhum comentário:

Postar um comentário