Reputation: 89
This is working
@PostMapping(value="/foo", params={"add"})
public String add(@ModelAttribute Foo foo) {
return "foo";
}
@PostMapping(value="/foo", params={"delete"})
public String delete(@ModelAttribute Foo foo) {
return "foo";
}
Why is this one NOT working ?
@PostMapping("/foo")
public String add(@ModelAttribute Foo foo, @RequestParam String add) {
return "foo";
}
@PostMapping("/foo")
public String delete(@ModelAttribute Foo foo, @RequestParam String delete) {
return "foo";
}
With @PostMapping, I get following error message.
Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'webController' method
Why am I getting ErrorMessage when using @RequestParam ?
Upvotes: 3
Views: 2044
Reputation: 358
Try this one,
@PostMapping("/foo")
public String add(@ModelAttribute Foo foo, @RequestParam("add") String add) {
return "foo";
}
@PostMapping("/foo")
public String delete(@ModelAttribute Foo foo, @RequestParam("delete") String delete){
return "foo";
}
It will work. Because you did not specify the param and simply use the string to two functions. So the compiler decide both are same function then only it throws the ambiguous error.
Upvotes: 0
Reputation: 2239
@RequestParam
is resolved at two different levels on where you are using it.
As per spring documentation, parameters are
Supported at the type level as well as at the method level! When used at the type level, all method-level mappings inherit this parameter restriction (i.e. the type-level restriction gets checked before the handler method is even resolved).
In your first case the controller differentiates the two requests different as it is resolved at the type level itself. When you use the @RequestParam
at the method level, you have the option of making the parameter as Optional
by setting the required
flag to false which makes it difficult to separate out your end points, hence the error.
Upvotes: 1