17+ years experience in software development. Worked extenseively on Java, JEE, Spring, open source, SOA, Webservices and such java related technologies. Currently working as Technical Architect at Mastek Ltd., India Ganesh has posted 4 posts at DZone. You can read more from them at their website. View Full User Profile

Tip: REST integration auto-binding javascript objects with controllers java objects

11.10.2011
| 3147 views |
  • submit to reddit

Often when developing REST services, the server rest controller implementations work on java objects and the REST clients usually javascript ajax calls work on javascript AJAX objects. Would'nt it be great to acheive automatic binding between the javascript and java objects, instead of writing explicit code to map to and from javascript and java objects. Below is a small sample giving example of just this, using Jersey REST controllers on server side and jquery ajax request on client side. Purposely chosen a POST request scenario instead of easier GET.

Under the hoods, on server side Jersey and Jackson provide the auto binding from incoming json object to java object

 REST controller with config

    @POST
    @Path("/directUpdate")
    @Produces(MediaType.TEXT_HTML)
    @Consumes(MediaType.APPLICATION_JSON)
    public void updatePartyInfo(Party input) throws IOException{
        
        System.out.println("input param party object"+input);

        Party party = service.getByPk(input.getPartyId());
        party.setName(input.getName());
        party.setAddress(input.getAddress());
        party.setTelephone(input.getTelephone());
        party.setDescription(input.getDescription());
        service.update(party);
        

        //redirecting to subsequent page
        servletResponse.sendRedirect("http://hostname:portnum/jqueryrest/partylist.html");

    }

 

 

jQuery Ajax request on client side

    function updateParty(){
        inputData = new Object();
        inputData.partyId = $("#partyId").val();
        inputData.name = $("#name").val();
        inputData.address = $("#address").val();
        inputData.telephone = $("#telephone").val();
        inputData.description = $("#description").val();
       
        jQuery.ajax ({
            url: 'http://hostname:portnum/jqueryrest/restful/party/directUpdate',
            type: "POST",
            processData: "false",
            data: JSON.stringify(inputData),
            dataType: "json",
            contentType: "application/json",
            success: function(){
                alert('Party update success');
            }
        });

    }

0
Published at DZone with permission of its author, Ganesh Ghag.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: