Question
How can I get parameters from a POST request in Spring MVC?
@PostMapping("/submit")
public String submitForm(@RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "result";
}
Answer
In Spring MVC, retrieving parameters from a POST request is straightforward and can be done using the `@RequestParam` annotation. This allows you to map request parameters to method arguments in your controller.
@PostMapping("/submit")
public String submitForm(@RequestParam("name") String name, @RequestParam("age") int age, Model model) {
model.addAttribute("name", name);
model.addAttribute("age", age);
return "result";
}
Causes
- The parameters may not be included in the request body or URL correctly.
- The method signature may not match the request mapping due to misconfigured annotations.
Solutions
- Use the `@RequestParam` annotation to bind a web request parameter to a method parameter in your controller.
- Ensure that your form or AJAX request is sending the data in the correct format (e.g., application/x-www-form-urlencoded).
- Check that the endpoint matches the URL of your POST request.
Common Mistakes
Mistake: Not using `@RequestParam` for parameter binding
Solution: Ensure that you annotate method parameters in your controller with `@RequestParam`.
Mistake: Sending parameters in the wrong format
Solution: Check your client's request format; ensure parameters are included in the request body appropriately.
Helpers
- Spring MVC
- POST request parameters
- @RequestParam
- Spring controller
- HTTP POST method