首页 > 解决方案 > REST 路径参数与资源路径冲突?

问题描述

这个问题是在我使用 JAX-RS 构建后端时出现的,但这确实适用于任何 REST API。

JAX-RS 如何处理可能由于参数路径变量而发生冲突的路径?假设你有

@POST
@Path('createBox/{boxName}')
foo()

@POST
@Path('createBox/small')
bar()

有人想用路径参数参数调用第一个端点small。在这种情况下会发生什么?如果foo()bar()有不同的帕尔马(也许像@FormParam),那会有助于区分吗?如果它们完全一样,没有参数怎么办?行为是不确定的吗?

标签: javaapirestjax-rs

解决方案


Reference : RESTful Java with JAX-RS 2.0, 2nd Edition by Bill Burke

  1. "/customers/{id : .+} <-- getCustomer
  2. "/customers/{id : .+}/address" <-- getAddress

Precedence rules

The JAX-RS specification has defined strict sorting and precedence rules for matching URI expressions and is based on a most specific match wins algorithm.

  1. The primary key of the sort is the number of literal characters in the full URI matching pattern and is in descending order ( 11 in getCustomer vs 18 in getAddress)
  2. The secondary key of the sort is the number of template expressions embedded within the pattern—that is, {id} or {id : .+}. This sort is in descending order.
  3. The tertiary key of the sort is the number of nondefault template expressions. A default template expression is one that does not define a regular expression—that is, {id}

Your example:

bar() wins because as per rule 1, it has more literal characters


推荐阅读