Tuesday, November 15, 2011

Rest Integration autobinding javascript objects with controller java objects

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');
            }
        });

    }

2 comments:

Ganesh Ghag said...

yes spring mvc annotations @ResponseBody and @RequestBody will do this auto-binding between javascript and java, under wraps spring also uses Jackson serializers. Also Spring controllers can be confifured to have a content negotiator, so when client is aksing for json, it will give jason else will server tradition java object to server view(jsp)

Ecommerce developer said...

Good work! I enjoyed enough reading your article . It was so helpful. I am Waiting for your next entry.