Spring MVC - Dlaczego nie można razem używać @RequestBody i @RequestParam
Używanie klienta HTTP dev z żądaniem Post i aplikacją Content-Type / x-www-form-urlencoded
1) Tylko @RequestBody
Request - localhost: 8080 / SpringMVC / welcome In Body - name = abc
Kod-
@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestBody String body, Model model) {
model.addAttribute("message", body);
return "hello";
}
// Daje treść jako 'name = abc' zgodnie z oczekiwaniami
2) Tylko @RequestParam
Request - localhost: 8080 / SpringMVC / welcome In Body - name = abc
Kod-
@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestParam String name, Model model) {
model.addAttribute("name", name);
return "hello";
}
// Podaje nazwę jako „abc” zgodnie z oczekiwaniami
3) Obie razem
Request - localhost: 8080 / SpringMVC / welcome In Body - name = abc
Kod-
@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestBody String body, @RequestParam String name, Model model) {
model.addAttribute("name", name);
model.addAttribute("message", body);
return "hello";
}
// Kod błędu HTTP 400 - Żądanie wysłane przez klienta było niepoprawne składniowo.
4) Zmieniono pozycję powyżej z pozycją params
Request - localhost: 8080 / SpringMVC / welcome In Body - name = abc
Kod-
@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestParam String name, @RequestBody String body, Model model) {
model.addAttribute("name", name);
model.addAttribute("message", body);
return "hello";
}
// Żaden błąd. Nazwa to „abc”. ciało jest puste
5) Razem, ale otrzymamy parametry url typu
Request - localhost: 8080 / SpringMVC / welcome? Name = xyz In Body - name = abc
Kod-
@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestBody String body, @RequestParam String name, Model model) {
model.addAttribute("name", name);
model.addAttribute("message", body);
return "hello";
}
// nazwa to „xyz”, a body to „name = abc”
6) Tak samo jak 5), ale z pozycją parametrów zmieniono
Kod -
@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestParam String name, @RequestBody String body, Model model) {
model.addAttribute("name", name);
model.addAttribute("message", body);
return "hello";
}
// nazwa = 'xyz, abc' ciało jest puste
Czy ktoś może wyjaśnić to zachowanie?