spring 使用不同的参数为相同的 url 模式创建两种方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15853035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 05:51:16  来源:igfitidea点击:

create two method for same url pattern with different arguments

springspring-mvc

提问by Vikas Singh

I have scenario where one url "serachUser" may come with two different value (request parameter) userId or UserName.

我有一个场景,其中一个 url“serachUser”可能带有两个不同的值(请求参数)userId 或 UserName。

so for this I have created two methods

所以为此我创建了两种方法

public String searchUserById(@RequestParam long userID, Model model) 
public ModelAndView searchUserByName(@RequestParam String userName)

But i am getting Ambiguous mapping found exception. Spring has any way to handle this situation.

但是我发现了模糊映射发现异常。Spring 有办法处理这种情况。

回答by kryger

You can use the paramsparameter to filter by HTTP parameters. In your case it would be something like:

您可以使用该params参数按 HTTP 参数进行过滤。在你的情况下,它会是这样的:

@RequestMapping(value = "/searchUser", params = "userID")
public String searchUserById(@RequestParam long userID, Model model) {
  // ...
}

@RequestMapping(value = "/searchUser", params = "userName")
public ModelAndView searchUserByName(@RequestParam String userName) {
  // ...
}