8

Consider three REST resources:

/persons/id/{id}
/persons/code/{code}
/persons/email/{email}

I want to make one method in a Spring MVC controller to handle these requests:

@RequestMapping("/persons/{searchField}/{searchValue}")
public Person search(@PathVariable field, @PathVariable value) {
...
}

The question: is there any elegant way to restrict searchField's variable list of values on the annotation level except just by checking them in the method search?

switch (field) {
  case "id": ...
  case "code": ...
  ...
  default: // not found exception??
}
4
  • 3
    Don't. Define three methods with the appropriate path each. Commented Sep 16, 2016 at 14:39
  • The elegant way is to define a method for each acceptable value of searchField, as noted by Sotirios above Commented Sep 16, 2016 at 14:40
  • how about @RequestMapping("/persons) and use RequestParam instead of PathVariable? Commented Sep 16, 2016 at 14:42
  • 1
    @SotiriosDelimanolis I actually can do it easily, see my answer :-D Commented Sep 16, 2016 at 14:43

2 Answers 2

19

It can be easily done using regular expressions in the mapping:

@RequestMapping("/persons/{searchField:id|code|email}/{searchValue}")
Sign up to request clarification or add additional context in comments.

1 Comment

Worth to mention, with such mapping the swagger (if someone uses it) will generate a request METHOD /persons/{searchField} (with no info about possible values that'll be matched), so for generating documentation we would need to add additional @Schema parameters.
2

You can also use a enum as type for your @PathVariable that will make Spring to limit the accepeted request values to the values of the enum

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.