首頁 >Java >java教程 >如何使用 Ajax 在沒有支援物件的情況下將多個變數傳遞到 Spring MVC 控制器?

如何使用 Ajax 在沒有支援物件的情況下將多個變數傳遞到 Spring MVC 控制器?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-15 13:32:03451瀏覽

How to Pass Multiple Variables to a Spring MVC Controller Using Ajax Without a Backing Object?

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 object to receive the JSON data directly. This allows you to access the values by their keys:

@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:

  • If strongly-typed parameters are required, you can create a custom POJO to represent the expected JSON structure and use @RequestBody to bind to it.
  • For simple cases, using @RequestParam in the query string or @PathVariable in the request URI can be more convenient for passing individual variables.

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn