Passing Multiple Variables to a Spring MVC Controller using Ajax
When using @RequestBody to pass multiple variables to a Spring MVC controller, it is not necessary to wrap them in a backing object. However, there are alternative approaches that can provide more flexibility or simplify the handling of JSON data.
Option 1: Use a Map
If you do not require strongly-typed parameters, you can use a Map
@RequestMapping(value = "/Test", method = RequestMethod.POST) @ResponseBody public boolean getTest(@RequestBody Map<String, String> json) { //json.get("str1") == "test one" }
This approach does not require a custom backing object and can handle JSON data with arbitrary keys.
Option 2: Use Jackson's ObjectNode
For more flexibility, you can bind to com.fasterxml.jackson.databind.node.ObjectNode to access the JSON data as a full JSON tree:
@RequestMapping(value = "/Test", method = RequestMethod.POST) @ResponseBody public boolean getTest(@RequestBody ObjectNode json) { //json.get("str1").asText() == "test one" }
This approach allows you to dynamically process the JSON data and extract values based on their JSON path.
Other Considerations:
The above is the detailed content of How to Pass Multiple Variables to a Spring MVC Controller Using Ajax Without a Backing Object?. For more information, please follow other related articles on the PHP Chinese website!