Home  >  Article  >  Java  >  How to Pass Multiple Parameters to a Spring MVC Controller using @RequestBody with Ajax?

How to Pass Multiple Parameters to a Spring MVC Controller using @RequestBody with Ajax?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 12:47:02949browse

How to Pass Multiple Parameters to a Spring MVC Controller using @RequestBody with Ajax?

Passing Multiple Parameters in @RequestBody to a Spring MVC Controller using Ajax

When attempting to pass multiple parameters to a Spring MVC controller using @RequestBody, many developers encounter the question of whether it's necessary to wrap the parameters in a backing object.

Initial Approach:

Initially, you may try to do the following:

@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody String str1, @RequestBody String str2) {}

With a JSON payload like this:

{
    "str1": "test one",
    "str2": "two test"
}

However, you may find that this approach doesn't work as expected.

Wrapper Object Approach:

To overcome this issue, the next approach is to wrap the parameters in a backing object:

@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody Holder holder) {}

This requires a JSON payload like this:

{
    "holder": {
        "str1": "test one",
        "str2": "two test"
    }
}

Alternative Options:

Alternatively, you could change the RequestMethod to GET and use @RequestParam in the query string. Another option is to use @PathVariable with either RequestMethod.

Using a Map or ObjectNode:

If wrapping in a backing object is undesirable, you can use a Map or Jackson's ObjectNode to bind multiple parameters in @RequestBody:

@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody Map<String, String> json) {
    //json.get("str1") == "test one"
}

Or:

public boolean getTest(@RequestBody ObjectNode json) {
    //json.get("str1").asText() == "test one"
}

The above is the detailed content of How to Pass Multiple Parameters to a Spring MVC Controller using @RequestBody with Ajax?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn