The hole spring MVC encountered in receiving ajax request parameters

ajax send request background does not receive parameters

In the process of project construction, the spring MVC controller always fails to receive the front-end ajax request parameter, which is null. The specific code is as follows:
Front end ajax Code:

$.ajax({
        headers: {
            'Content-type': 'application/json; charset=utf-8'
        },
        url : getContextPath()+"/groupUserRel/insert",
        data :{
            "groupId": "80901",
            "userName": name,
            "userMobile": tel,
            "address": address,
            "userWeightCount": weight,
            "userSendCount": number
        },
        dataType: 'json',
        type:"POST",
        success : function(response) {
            console.log(response);
        }
  })

controller code:

@RequestMapping(value = "insert")
@ResponseBody
public Result<Boolean> insert(ProGroupUserRelVo vo) {
        Result<Boolean> result = new Result<>(false);
        System.out.println(vo);
        return result;
 }

After continuous attempts, it is found that the problem lies in the request header of ajax: 'content type': 'application/json; charset=utf-8'. This parameter setting specifies that the parameter type to be transmitted to the background is json format, but the one transmitted by ajax is not json string, so it needs to be changed as follows:

1, Solution 1

1. Convert the data in the ajax request to json string, using JSON.stringify(s) Function complete conversion

$.ajax({
        headers: {
            'Content-type': 'application/json; charset=utf-8'
        },
        url : getContextPath()+"/groupUserRel/insert",
        data : JSON.stringify({
            "groupId": "80901",
            "userName": name,
            "userMobile": tel,
            "address": address,
            "userWeightCount": weight,
            "userSendCount": number
        }),
        dataType: 'json',
        type:"POST",
        success : function(response) {
            console.log(response);
        }
  })

2. The background code adds @ RequestBody annotation to the received parameter object

@RequestMapping(value = "insert")
@ResponseBody
public Result<Boolean> insert(@RequestBody ProGroupUserRelVo vo) {
        Result<Boolean> result = new Result<>(false);
        System.out.println(vo);
        return result;
 }

This allows mapping to parameters

2, Solution 2

Remove the content type in the ajax request header directly, and let ajax send the default content type: application / x-www-form-urlencoded, so that springmvc can parse by itself, without telling springmvc how to parse

Tags: JSON Spring

Posted on Fri, 15 May 2020 13:02:28 -0400 by cpd259