Home > Java > javaTutorial > body text

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

Mary-Kate Olsen
Release: 2024-11-15 13:32:03
Original
343 people have browsed it

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"
}
Copy after login

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"
}
Copy after login

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.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template