ajax passes object parameters to springmvc

In the process of using the front-end ajax technology, sometimes we simply pass parameters to the springmvn in the background, and use the following code directly: (jquery's ajax code)

var options = {
    url: 'helloworld',
    method: 'get',
    dataType: 'json',
    data: {
        teamId: 123
    },
    success: function (rs) {
        // code here
    },
    error: function (rs) {
        // code here
    }
};
$.ajax(options);

 Background springmvc code:

@RequestMapping(value = { "/helloworld" }, method = { RequestMethod.GET })
@ResponseBody
public Boolean helloworld(@RequestParam("teamId") Long teamId)  {
    LOGGER.debug("start to helloworld. teamId:{}", teamId);
   
    Boolean rs = null; // coder here
    LOGGER.debug("finish helloworld. teamId:{}", teamId);
    return rs;
}

 The above is also commonly used.

But sometimes we need to use ajax to pass objects to the background, how to do it? The front end passes JavaScript objects, and the backend receives Java objects. springmvn does the json conversion from JavaScript objects to Java objects for us. as follows:

var paramsArr = [];
for(var i = 0; i < 10; i++) {
    var obj = {
        id: i,
        name: 'name-' + i
    };
    paramsArr.push(obj);
}

var options = {
    url: 'helloworld',
    method: 'post', // Note here, the object is passed to the background, here must be POST, otherwise the object cannot be encapsulated into the body of POST
    dataType: 'json',
    contentType: 'application/json', // Note here, the object is passed to the background, here must be application/json
    data: JSON.stringify(paramsArr), // Note that the object is passed to the background, and the object must be serialized here
    success: function (rs) {
        // code here
    },
    error: function (rs) {
        // code here
    }
};
$.ajax(options);

 

class Person {
    private Long id;
    private String name;
    // setter / getter here
}

/**
 *
 * Note the @RequestBody in the parameter. It will read the data stream in the body of the POST request, and then deserialize the JSON to a java object.
 */
@RequestMapping(value = { "/helloworld" }, method = { RequestMethod.POST })
@ResponseBody
public Boolean helloworld(@RequestBody List<Person> persons)  {
    LOGGER.debug("start to helloworld. persons:{}", persons);
   
    Boolean rs = null; // coder here
    LOGGER.debug("finish helloworld. persons:{}", persons);
    return rs;
}

This way the object parameter can be passed to the backend.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326180997&siteId=291194637