create two method for same url pattern with different arguments

SpringSpring Mvc

Spring Problem Overview


I have scenario where one url "serachUser" may come with two different value (request parameter) userId or 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. Can Spring handle this situation?

Spring Solutions


Solution 1 - Spring

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

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

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

Solution 2 - Spring

Any way incase of request param null is allowed if you don't pass any value it will be null then you can write your coad like:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVikas SinghView Question on Stackoverflow
Solution 1 - SpringkrygerView Answer on Stackoverflow
Solution 2 - SpringTek.SailendraView Answer on Stackoverflow