如何将Ason的Json对象传递给Spring MVC Controller?
问题内容:
我正在使用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.html",
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
}
该类的优点是,将来可以根据需要向该类添加更多变量。
例如。 如果要实现排序功能。