Mark Lutton
Mark Lutton

Reputation: 7007

How is dispatching controlled in JAX-RS?

I'm writing a RESTful Web Service with RESTeasy. This is an implementation of JAX-RS. You annotate a class or method with a single @Path annotation. Regular expressions are used to get path parameters. For instance

@Path("/foo{varname:.*}/bar")

matches all patterns starting with "/foo", ending with "/bar" and having anything in between. Whatever is in between is assigned to a parameter named varname.

Some frameworks (like Django) have a list of regular expressions and methods that will be tried in order. For instance /john/q/smith, /john/{.*}/smith, /john/{.*}/{.*}. "/john/henry/smith" matches the second and third, but the second one will be dispatched because it is the first match found.

Is this possible in JAX-RS, or is there no inherent order to the classes and methods? For /john/{.*}/{.*} would you have to write a regex that means /john/anything/anythingbutsmith? You would have to change it every time you changed the other ones.

Upvotes: 2

Views: 518

Answers (2)

Anil Singh
Anil Singh

Reputation: 21

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. The JAX-RS provider gathers up the set of deployed URI expressions and sorts them based on the following logic:

  1. The primary key of the sort is the number of literal characters in the full URI matching pattern. The sort is in descending order. In our ambiguous example, getCustomer()’s pattern has 11 literal characters: /customers/. The getAd dress() method’s pattern has 18 literal characters: /customers/ plus address. Therefore, the JAX-RS provider will try to match getAddress()’s pattern before getCustomer().

  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}.

Upvotes: 0

djna
djna

Reputation: 55897

There is a well defined algorithm, section 3.7.1 of the JAX-RS spec describes it. Frankly, I find the explanation pretty opaque - so reading it, I can't answer your question.

However, I've just found the CXF overview of the selection alogorithm, and that seems to indicate that the precedence rules do indeed let you do what you want.

Upvotes: 2

Related Questions