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) {}
requires a JSON structure with each variable explicitly declared:
{ "str1": "test one", "str2": "two test" }
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) {}
which can be used with the following JSON:
{ "holder": { "str1": "test one", "str2": "two test" } }
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" }
For an ObjectNode:
public boolean getTest(@RequestBody ObjectNode json) { //json.get("str1").asText() == "test one" }
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!