【问题标题】:Overload Controller Method in Java SpringJava Spring中的重载控制器方法
【发布时间】:2015-05-21 17:25:28
【问题描述】:

我有一个控制器,它需要在不同的 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 参数选择方法?

【问题讨论】:

  • 解释似乎不起作用。你期望它做什么?你为什么会有这些期望?它的实际表现如何?
  • 感谢您的提问,我扩展了我的帖子。
  • 只使用一种方法,将@RequestParamrequired设置为false
  • 这不是我真正想做的:事实上我有超过 2 个参数,当我只使用一种方法时,这会导致很多 if 和 else。此外,将非常不同的行为强制到一种方法中似乎并不是很 java-esk。
  • 可能值得注意的是,控制器的 @RequestMapping 方法的名称根本不重要。

标签: java spring


【解决方案1】:

在映射中指明应该存在哪些参数

@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) {
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 2019-09-07
    • 1970-01-01
    相关资源
    最近更新 更多