springmvc可以从post json获取数据,但是从post key-value对中获取null,为什么?

时间:2017-08-03 06:06:54

标签: jquery spring-mvc post

如果我在jquery中post json,然后可以使用@RequestBody

在springmvc中获取数据
$.ajax({
        url:"menu_selectByName",
        method:"post",
        data:JSON.stringify({menuName:"index"}),
        contentType:"application/json",
        success:function(res){
            $scope.content = res;
        }}
)

@RequestMapping(value = "/menu_selectByName") 
@ResponseBody
public Menu selectByName(@RequestBody String json){
    //json = "{"menuName":"index"}"
    System.out.println(json):

    //other operations
}

但如果我使用x-www-form-urlencoded发布键值对,则springmvc无法获取数据

$.ajax({
        url:"menu_selectByName",
        method:"post",
        data:{menuName:"index"},
        contentType:"application/x-www-form-urlencoded",
        success:function(res){
            $scope.content = res;
        }}
)

@RequestMapping(value = "/menu_selectByName")
@ResponseBody
public Menu selectByName(String menuName){
    //menuName = null
    System.out.println(menuName);
    return  menuService.selectByName(menuName);
}

如果我这样写:

@RequestMapping(value = "/menu_selectByName")
@ResponseBody
public Menu selectByName(@RequestParam("menuName") String menuName){
    //menuName = null
    System.out.println(menuName);
    return  menuService.selectByName(menuName);
}

它将报告

  HTTP Status 400 – Bad Request

  Type:Status Report

  Message:Required String parameter 'menuName' is not present

  Description:The server cannot or will not process the request due to 
something that is perceived to be a client error (e.g., malformed request 
syntax, invalid request message framing, or deceptive request routing).

我在哪里弄错了?

0 个答案:

没有答案