Explain Codes LogoExplain Codes Logo

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

java
spring-mvc
ajax
request-body
Alex KataevbyAlex Kataev·Jan 6, 2025
TLDR

To transmit multiple variables, POJO acts as the @RequestBody. It allows for a crisp, single-object payload in an Ajax request.

// POJO holding all the variables public class DataBundle { private String text; private int number; // ... getters and setters ... // POJOs are the unsung heroes of data transfer! } // Spring controller method @PostMapping("/processData") public void handleData(@RequestBody DataBundle data) { // Leveraging data.getText(), data.getNumber() // If only handling data were always this easy }

Assemble a JSON using jQuery Ajax that corresponds with your POJO:

$.ajax({ url: '/processData', method: 'POST', contentType: 'application/json', data: JSON.stringify({ text: 'example', number: 42 }), success: function() { /* Celebrate success, maybe with a cake? */ } }); // Note to reader: 'text' and 'number' fields in the JSON are like twins with the POJO class fields.

Bountiful alternatives: When POJOs don't cut it

Sometimes POJOs could feel like using a sledgehammer to crack a walnut! Here are other approaches radiating more flexibility:

Map with @RequestBody: Easy-Peasy

No need for a POJO, deploy a Map to save the day:

@PostMapping("/processDataMap") public void handleDataMap(@RequestBody Map<String, Object> dataMap) { // Extract variables using keys 'text' and 'number' // Maps: the Jacks of all trades }

ObjectNode from Jackson: When it gets complicated

For elaborate or dynamic JSON structures, ObjectNode becomes your flexible friend:

@PostMapping("/processDataDynamic") public void handleDataObjectNode(@RequestBody ObjectNode objectNode) { // objectNode.get("text"), because JSON doesn't scare us }

Custom handler with HandlerMethodArgumentResolver: Your Way

Want more control? Write your individual HandlerMethodArgumentResolver:

public class CustomDataBundleResolver implements HandlerMethodArgumentResolver { // Implement the methods to resolve arguments from the request. // Who said it isn't possible to reinvent the wheel? }

And link it in your Spring MVC configuration. Spring, where magicians keep their tricks!

Fortress: Secure and robust handling of request parameters

Safety first: Secure Handling of @RequestBody

Remember to filter and validate your input, or the big bad wolf might huff and puff and inject your SQL:

public class SafeDataBundle { @NotNull private String safeText; @Min(0) private int safeNumber; // getter and setter methods with superhero powers }

The Mix: Combining Various Request Parameters

For simple types, mix @RequestBody with @RequestParam or @PathVariable:

@PostMapping("/processDataMix/{pathId}") public void handleDataMix(@PathVariable int pathId, @RequestParam String query, @RequestBody DataBundle data) { // Now we have path, query and body parameters, what a combo! }

The MasterChef: Dealing with Complex Scenarios

For complex JSON hierarchies or partial deserialization, Jackson Mix-in annotations or JSON Views can serve well.