Home > Java > javaTutorial > 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
Release: 2024-11-11 12:47:02
Original
1009 people have browsed it

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) {}
Copy after login

With a JSON payload like this:

{
    "str1": "test one",
    "str2": "two test"
}
Copy after login

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) {}
Copy after login

This requires a JSON payload like this:

{
    "holder": {
        "str1": "test one",
        "str2": "two test"
    }
}
Copy after login

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"
}
Copy after login

Or:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template