如何将json对象从ajax传递给spring mvc控制器?

我正在使用SpringMVC,我将数据从ajax传递给控制器​​,但是我的控制器中有空值,请检查我的代码如下

function searchText()
{
   var sendData = {
    "pName" : "bhanu",
     "lName" :"prasad"
   }
  $.ajax({
type: "POST",
 url: "/gDirecotry/ajax/searchUserProfiles.htm,
    async: true,
    data:sendData,
    success :function(result)
    {
    }
 }

MyControllerCode

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

       public  @ResponseBody String  getSearchUserProfiles(HttpServletRequest request)
       {
         String pName = request.getParameter("pName");
         //here I got null value
       }

任何一个帮助我

最佳答案
嗨,享受以下代码.

Javascript AJAX调用

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

}

弹簧控制器代码

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
   }

以下搜索类将如下

class Search {
    private String pName;
    private String lName;

    // getter and setters for above variables
}

这个类的优点是,将来如果需要,您可以在此类中添加更多变量.
例如.如果你想实现排序功能.

转载注明原文:如何将json对象从ajax传递给spring mvc控制器? - 代码日志