我有一个 Controller ,它需要在不同的 URL 参数下表现出不同的行为。像这样的:
@RequestMapping(method = RequestMethod.GET)
public A getA(@RequestParam int id, @RequestParam String query) {
...
}
@RequestMapping(method = RequestMethod.GET)
public A getA(@RequestParam int id) {
...
}
但这似乎不起作用,我得到以下异常:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map '[controller name]' bean method
应用程序是否可以根据 URL 参数选择方法?
最佳答案
在映射中指明应该存在哪些参数
@RequestMapping(method = RequestMethod.GET, params = {"id", "query"})
public A getA(@RequestParam int id, @RequestParam String query) {
...
}
@RequestMapping(method = RequestMethod.GET, params = {"id"})
public A getA(@RequestParam int id) {
...
}
从 Spring MVC 4.3 版开始,新的 @GetMapping
、@PostMapping
和类似的注解也有这个 params
元素可以使用
@GetMapping(params = {"id"})
public A getA(@RequestParam int id) {
...
}
https://stackoverflow.com/questions/30380498/