Using HTTP dev client with Post request and Content-Type application/x-www-form-urlencoded
1) Only @RequestBody
URL: localhost:8080/SpringMVC/welcome
Body: name=abc
@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestBody String body, Model model) {
model.addAttribute("message", body);
return "hello";
}
// Gives body as 'name=abc' as expected
2) Only @RequestParam
URL: localhost:8080/SpringMVC/welcome
In Body - name=abc
@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestParam String name, Model model) {
model.addAttribute("name", name);
return "hello";
}
// Gives name as 'abc' as expected
3) Both together
URL: localhost:8080/SpringMVC/welcome
Body: name=abc
@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";
}
// HTTP Error Code 400 - The request sent by the client was syntactically incorrect.
4) Above with params position changed
URL: localhost:8080/SpringMVC/welcome
Body: name=abc
@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";
}
// No Error. Name is 'abc'. body is empty
5) Together but get type url parameters
URL: localhost:8080/SpringMVC/welcome?name=xyz
Body: name=abc
@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";
}
// name is 'xyz' and body is 'name=abc'
6) Same as 5) but with parameters position changed
@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";
}
// name = 'xyz,abc' body is empty
Can someone explain this behaviour?
See Question&Answers more detail:
os