Spring MVC中特定路径变量的可能值列表

时间:2016-09-16 14:37:52

标签: java spring rest spring-mvc

考虑三个REST资源:

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

我想在Spring MVC控制器中创建一个方法来处理这些请求:

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

问题是:是否可以优雅地限制searchField注释级别的值变量列表,只是在方法search中检查它们? / p>

switch (field) {
  case "id": ...
  case "code": ...
  ...
  default: // not found exception??
}

2 个答案:

答案 0 :(得分:9)

可以使用映射中的regular expression轻松完成:

@RequestMapping("/persons/{searchField:id|code|email}/{searchValue}")

答案 1 :(得分:0)

您还可以使用枚举作为@PathVariable的类型,使Spring将加密的请求值限制为枚举值