REST中的子资源和路径变量冲突? [英] Subresource and path variable conflicts in REST?

查看:184
本文介绍了REST中的子资源和路径变量冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设计可能在路径解析度上含糊不清的REST API是否被认为是不好的做法?例如:

Is it considered bad practice to design a REST API that may have an ambiguity in the path resolution? For example:

GET /animals/{id}   // Returns the animal with the given ID
GET /animals/dogs   // Returns all animals of type dog

好的,这是人为的,因为您实际上只是执行GET /dogs,但是希望它可以说明我的意思.从路径解析的角度来看,似乎您不知道要寻找带有id="dogs"还是仅包含dogs

Ok, that's contrived, because you would actually just do GET /dogs, but hopefully it illustrates what I mean. From a path resolution standpoint, it seems like you wouldn't know whether you were looking for an animal with id="dogs" or just all the dogs

特别是,我对Jersey能否解决此问题感兴趣.如果您知道id是整数怎么办?

Specifically, I'm interested in whether Jersey would have any trouble resolving this. What if you knew the id to be an integer?

推荐答案

特别是,我对Jersey能否解决这个问题很感兴趣"

"Specifically, I'm interested in whether Jersey would have any trouble resolving this"

不,这不是问题.如果您查看 JAX-RS规范§ 3.7.2 ,您将看到用于将请求与资源方法进行匹配的算法.

No this would not be a problem. If you look at the JAX-RS spec § 3.7.2, you'll see the algorithm for matching requests to resource methods.

[ E 是一组匹配方法] ...

[E is the set of matching methods]...

使用每个成员中文字字符的数量作为主键(降序),捕获组的数量作为辅助键(降序)以及使用以下内容的捕获组数对 E 进行排序非默认正则表达式(即不是'([[^/] +?)')作为三级键(降序)

Sort E using the number of literal characters in each member as the primary key (descending order), the number of capturing groups as a secondary key (descending order) and the number of capturing groups with non-default regular expressions (i.e. not ‘([^ /]+?)’) as the tertiary key (descending order)

所以从根本上说,文字字符的数量是排序的主键(请注意,这是短路的;您赢得了主要,您就赢得了).因此,例如,如果请求发送到/animals/cat,则显然@Path("/animals/dogs")不在集合中,因此我们不必担心.但是,如果请求是/animals/dogs,则这两个方法都将在集合中.然后根据文字字符的数量对集合进行排序.由于@Path("/animals/dogs")具有比@Path("/animals/")更多的文字字符,因此前者获胜.捕获组{id}不计入文字字符.

So basically it's saying that the number of literal characters is the primary key of which to sort by (note that it is short circuiting; you win the primary, you win). So for example if a request goes to /animals/cat, @Path("/animals/dogs") would obviously not be in the set, so we don't need to worry about it. But if the request is to /animals/dogs, then both methods would be in the set. The set is then sorted by the number of literal characters. Since @Path("/animals/dogs") has more literal characters than @Path("/animals/"), the former wins. The capturing group {id} doesn't count towards literal characters.

如果您知道id是整数怎么办?"

"What if you knew the id to be an integer?"

捕获组允许使用正则表达式.因此,您可以使用@Path("/animals/{id: \\d+}").除非数字为/animals/dogs,否则任何非数字的值都不会传递并导致404.

The capture group allows for regex. So you can use @Path("/animals/{id: \\d+}"). Anything not numbers will not pass and lead to a 404, unless of course it is /animals/dogs.

这篇关于REST中的子资源和路径变量冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆