131

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?

2 Answers 2

258

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) {
  // ...
}
Sign up to request clarification or add additional context in comments.

10 Comments

The other way I had handled this is to accept the parameter as a String, then call Long.parseLong() on it. If it parses, then its the the userId, if it doesn't, assume its the username.
In case you want to know how it works when you have multiple params, you can use params = { "storeId", "containerLabel" }
if url mapping and all other parameters are same, is it give a deployment time exception?
But will it be possible to assign different role/function to this url to authorise?
Related: Swagger might not fully support this. I found this issue github.com/springfox/springfox/issues/1828. I use Spring Fox 2.7.0 and the Swagger UI only shows 1 method instead of 2. Apparently this can be fixed by enableUrlTemplating(true) and using an experimental Swagger UI: springfox.github.io/springfox/docs/current/…
|
-1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.