簡體   English   中英

Java Spring中的重載控制器方法

[英]Overload Controller Method in Java Spring

我有一個控制器,它需要對不同的 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) {
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM