Question:
How can you pass multiple variables in the HTTP request body to a Spring MVC controller using Ajax? Specifically, can you use @RequestBody with individual parameters, or does it require a wrapping object?
Answer:
While @RequestBody typically maps to a single object, you can achieve your goal using either of the following methods:
Option 1: Using a Map
To avoid creating a custom backing object, you can map @RequestBody to a Map
@RequestMapping(value = "/Test", method = RequestMethod.POST) @ResponseBody public boolean getTest(@RequestBody Map<String, String> json) { //json.get("str1") == "test one" }
This allows you to access the individual variables from the JSON as properties of the map.
Option 2: Using an ObjectNode
If you prefer working with the full JSON tree, you can bind @RequestBody to Jackson's ObjectNode:
public boolean getTest(@RequestBody ObjectNode json) { //json.get("str1").asText() == "test one" }
This gives you direct access to the JSON structure and its various nodes.
Comparison:
Both options offer different approaches to handling multiple variables in @RequestBody:
Ultimately, the best choice depends on the specific needs of your application and the level of flexibility required.
The above is the detailed content of How to Pass Multiple Variables in @RequestBody Using Ajax and Spring MVC?. For more information, please follow other related articles on the PHP Chinese website!