Home  >  Article  >  Java  >  How to Pass Multiple Variables in @RequestBody Using Ajax and Spring MVC?

How to Pass Multiple Variables in @RequestBody Using Ajax and Spring MVC?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-10 01:40:02220browse

How to Pass Multiple Variables in @RequestBody Using Ajax and Spring MVC?

Passing Multiple Variables in @RequestBody Using Ajax and Spring MVC

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:

  • Using a Map simplifies access to individual values but requires a more manual approach to extracting them.
  • Using an ObjectNode provides more flexibility but may require additional handling to access specific values or iterate over the JSON tree.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn