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

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

Mary-Kate Olsen
發布: 2024-11-15 13:32:03
原創
459 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板