How to pass Json object from ajax to spring mvc controller?

Hey enjoy the following code.

Javascript AJAX call

function searchText() {
   var search = {
      "pName" : "bhanu",
      "lName" :"prasad"
   }

   $.ajax({
       type: "POST",
       contentType : 'application/json; charset=utf-8',
       dataType : 'json',
       url: "/gDirecotry/ajax/searchUserProfiles.html",
       data: JSON.stringify(search), // Note it is important
       success :function(result) {
       // do what ever you want with data
       }
   });
}

Spring controller code

RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)

public  @ResponseBody String  getSearchUserProfiles(@RequestBody Search search, HttpServletRequest request) {
    String pName = search.getPName();
    String lName = search.getLName();

    // your logic next
}

Following Search class will be as follows

class Search {
    private String pName;
    private String lName;

    // getter and setters for above variables
}

Advantage of this class is that, in future you can add more variables to this class if needed.

Eg. if you want to implement sort functionality.

Leave a Comment