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:
以上是如何使用 Ajax 在沒有支援物件的情況下將多個變數傳遞到 Spring MVC 控制器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!