我不是在问这里已经问过的问题: @PathParam和@QueryParam有什么区别

这是一个“最佳实践”或惯例问题。

什么时候使用@PathParam vs @QueryParam。

我能想到的是,这个决定可能是用这两者来区分信息模式。让我在下面说明我的LTPO -不完美的观察。

PathParam的使用可以保留在信息类别中,这将很好地归入信息树的一个分支。PathParam可以用于下钻到实体类层次结构。

然而,QueryParam可以保留用于指定属性以定位类的实例。

例如,

/ Vehicle /车?车主= 123 / House /克?该区域= newengland

(category) ?instance

@GET
@Path("/employee/{dept}")
Patient getEmployee(@PathParam("dept")Long dept, @QueryParam("id")Long id) ;

vs / category (instance)

@GET
@Path("/employee/{dept}/{id}")
Patient getEmployee(@PathParam("dept")Long dept, @PathParam("id")Long id) ;

vs ?类别+实例

@GET
@Path("/employee")
Patient getEmployee(@QueryParam("dept")Long dept, @QueryParam("id")Long id) ;

我不认为这样做有一个标准的惯例。是吗?然而,我想知道人们如何使用PathParam和QueryParam来区分他们的信息,就像我上面举例的那样。我也很想知道这种做法背后的原因。


当前回答

您可以同时支持查询参数和路径参数,例如,在资源聚合的情况下——当子资源的集合本身有意义时。

/departments/{id}/employees
/employees?dept=id

查询参数可支持分层和非分层子集设置;路径参数仅分级。

资源可以显示多个层次结构。如果要查询跨层次边界的广泛子集合,则支持短路径。

/inventory?make=toyota&model=corolla
/inventory?year=2014

使用查询参数组合正交层次结构。

/inventory/makes/toyota/models/corolla?year=2014
/inventory/years/2014?make=toyota&model=corolla
/inventory?make=toyota&model=corolla&year=2014

在组合的情况下只使用路径参数——当一个资源脱离了它的父元素就没有意义了,而且所有子元素的全局集合本身并不是一个有用的资源。

/words/{id}/definitions
/definitions?word=id   // not useful

其他回答

REST本身可能不是一个标准,但是阅读一般的REST文档和博客文章应该会给你一些指导,让你更好地构造API url。大多数其他api倾向于在路径中只有资源名称和资源id。如:

/departments/{dept}/employees/{id}

一些REST api使用查询字符串进行过滤,分页和排序,但由于REST不是一个严格的标准,我建议检查一些REST api,如github和stackoverflow,看看什么可以很好地为您的用例工作。

我建议在路径中放入任何必需的参数,而任何可选参数都应该是查询字符串参数。当尝试编写匹配不同组合的URL处理程序时,在路径中放置可选参数最终会变得非常混乱。

来自维基百科:统一资源定位器

包含数据的路径,通常以分层形式组织,显示为由斜杠分隔的段序列。

可选查询,以问号(?)与前一部分隔开,包含非分层数据的查询字符串。

-根据URL的概念设计,我们可以为分层数据/指令/定位器组件实现一个PathParam,或者当数据不是分层时实现一个QueryParam。这是有意义的,因为路径是自然有序的,而查询包含的变量可能是任意有序的(无序的变量/值对)。

之前的一位评论者写道,

我认为,如果参数标识一个特定的实体,您应该使用路径变量。

另一个写道:

使用@PathParam基于id进行检索。用户@QueryParam用于过滤器,或者如果你有任何用户可以传递的固定选项列表。

另一个,

我建议在路径中放入任何必需的参数,而任何可选参数都应该是查询字符串参数。

— However, one might implement a flexible, non-hierarchical system for identifying specific entities! One might have multiple unique indexes on an SQL table, and allow entities to be identified using any combination of fields that comprise a unique index! Different combinations (perhaps also ordered differently), might be used for links from various related entities (referrers). In this case, we might be dealing with non-hierarchical data, used to identify individual entities — or in other cases, might only specify certain variables/fields — certain components of unique indexes — and retrieve a list/set of records. In such cases, it might be easier, more logical and reasonable to implement the URLs as QueryParams!

Could a long hexadecimal string dilute/diminish the value of keywords in the rest of the path? It might be worth considering the potential SEO implications of placing variables/values in the path, or in the query, and the human-interface implications of whether we want users to be able to traverse/explore the hierarchy of URLs by editing the contents of the address bar. My 404 Not Found page uses SSI variables to automatically redirect broken URLs to their parent! Search robots might also traverse the path hierarchy. On the other hand, personally, when I share URLs on social media, I manually strip out any private unique identifiers — typically by truncating the query from the URL, leaving only the path: in this case, there is some utility in placing unique identifiers in the path rather than in the query. Whether we want to facilitate the use of path components as a crude user-interface, perhaps depends on whether the data/components are human-readable or not. The question of human-readability relates somewhat to the question of hierarchy: often, data that may be expressed as human-readable keywords are also hierarchical; while hierarchical data may often be expressed as human-readable keywords. (Search engines themselves might be defined as augmenting the use of URLs as a user-interface.) Hierarchies of keywords or directives might not be strictly ordered, but they are usually close enough that we can cover alternative cases in the path, and label one option as the "canonical" case.

对于每个请求的URL,我们可能会回答几种基本的问题:

我们要求/提供什么样的记录/东西? 我们对哪一个感兴趣? 我们希望如何呈现信息/记录?

Q1几乎肯定最好由路径或PathParams覆盖。 Q3(可能通过一组任意顺序的可选参数和默认值进行控制);几乎可以肯定QueryParams是最好的。 这要看情况……

我给一个例子来理解我们什么时候使用@Queryparam和@pathparam

例如,我正在使用一个资源是carResource类

如果你想让你的资源方法的输入是强制性的,那么使用参数类型为@pathaparam,如果你的资源方法的输入应该是可选的,那么保持参数类型为@QueryParam

@Path("/car")
class CarResource
{
    @Get
    @produces("text/plain")
    @Path("/search/{carmodel}")
    public String getCarSearch(@PathParam("carmodel")String model,@QueryParam("carcolor")String color) {
        //logic for getting cars based on carmodel and color
            -----
        return cars
    }
}

为这个资源传递请求

req uri ://address:2020/carWeb/car/search/swift?carcolor=red

如果你给出这样的要求,资源将给出基于汽车的型号和颜色

 req uri://address:2020/carWeb/car/search/swift

如果你给出这样的要求,资源方法将只显示基于快速模型的汽车

req://address:2020/carWeb/car/search?carcolor=red

如果你这样给出,我们会得到ResourceNotFound异常因为在car资源类中,我声明了carmodel为@pathPram也就是说,你必须并且应该将carmodel作为reQ uri,否则它不会将reQ传递给resource但如果你不传递颜色它也会将reQ传递给resource为什么呢因为颜色是@quetyParam,这在reQ中是可选的。

原因其实很简单。当使用查询参数时,你可以输入字符,如“/”,你的客户端不需要对它们进行html编码。还有其他原因,但这只是一个简单的例子。至于何时使用路径变量。我想说的是,当你处理id或者路径变量是一个查询的方向时。

我喜欢以下几点:

@PathParam

当需要参数时,例如ID, productNo .

GET /user/details/{ID}
GET /products/{company}/{productNo}

@QueryParam

当您需要传递可选参数,如过滤器,在线状态和他们可以为空

GET /user/list?country=USA&status=online
GET /products/list?sort=ASC 

同时使用时

GET /products/{company}/list?sort=ASC