gpt4 book ai didi

java - Java Spring中的重载 Controller 方法

转载 作者:IT老高 更新时间:2023-10-28 13:51:47 26 4
gpt4 key购买 nike

我有一个 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) {
...
}

关于java - Java Spring中的重载 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30380498/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com