Home > Java > javaTutorial > Can I Pass Multiple Variables to a Spring MVC Controller with @RequestBody without a Backing Object?

Can I Pass Multiple Variables to a Spring MVC Controller with @RequestBody without a Backing Object?

Linda Hamilton
Release: 2024-11-11 12:40:03
Original
1040 people have browsed it

Can I Pass Multiple Variables to a Spring MVC Controller with @RequestBody without a Backing Object?

Passing Multiple Variables in @RequestBody to Spring MVC Controller with Ajax

Question:

Is wrapping parameters in a backing object necessary for passing multiple variables in @RequestBody to a Spring MVC controller with Ajax?

Discussion:

The question stems from a need to pass two strings, "str1" and "str2," as JSON in the @RequestBody. However, the initial approach:

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

requires a JSON structure with each variable explicitly declared:

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

However, it is more convenient to use a backing object, as seen in:

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

which can be used with the following JSON:

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

Answer:

While using a backing object is a viable approach, an alternative solution is to use a Map or ObjectNode to bind directly to the JSON without creating a separate object class.

For a Map:

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

For an ObjectNode:

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

The above is the detailed content of Can I Pass Multiple Variables to a Spring MVC Controller with @RequestBody without a Backing Object?. 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