矩阵参数与查询参数

矩阵参数与查询参数

本文介绍了URL 矩阵参数与查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是在我的 URL 中使用矩阵还是查询参数.我发现对该主题的旧讨论并不令人满意.

I'm wondering whether to use matrix or query parameters in my URLs. I found an older discussion to that topic not satisfying.

示例

乍一看矩阵参数似乎只有优点:

At first sight matrix params seem to have only advantages:

  • 更具可读性
  • 没有编码和解码&"在 XML 文档中是必需的
  • 带有?"的网址在许多情况下不被缓存;带有矩阵参数的 URL 被缓存
  • 矩阵参数可以出现在路径的任何地方,不限于它的末尾
  • 矩阵参数可以有多个值:paramA=val1,val2

但也有缺点:

  • 只有少数框架如 JAX-RS 支持矩阵参数
  • 当浏览器通过 GET 提交表单时,参数变成查询参数.因此,对于同一个任务,它最终会得到两种参数.为了不混淆 REST 服务的用户并限制服务开发人员的工作量,在这方面使用始终查询参数会更容易.

由于服务的开发者可以选择支持矩阵参数的框架,唯一剩下的缺点就是浏览器默认创建查询参数.

Since the developer of the service can choose a framework with matrix param support, the only remaining disadvantage would be that browsers create by default query parameters.

还有其他缺点吗?你会怎么做?

Are there any other disadvantages? What would you do?

推荐答案

重要的区别在于,矩阵参数适用于特定的路径元素,而查询参数适用于整个请求.这在对多个级别的资源和子资源进行复杂的 REST 样式查询时发挥作用:

The important difference is that matrix parameters apply to a particular path element while query parameters apply to the request as a whole. This comes into play when making a complex REST-style query to multiple levels of resources and sub-resources:

http://example.com/res/categories;name=foo/objects;name=green/?page=1

这真的归结为命名空间.

It really comes down to namespacing.

注意:这里的资源级别"是categoriesobjects.

Note: The 'levels' of resources here are categories and objects.

如果只对多级 URL 使用查询参数,您将得到

If only query parameters were used for a multi-level URL, you would end up with

http://example.com/res?categories_name=foo&objects_name=green&page=1

这样你也会失去请求中参数的局部性所增加的清晰度.此外,在使用 JAX-RS 等框架时,所有查询参数都会出现在每个资源处理程序中,从而导致潜在的冲突和混乱.

This way you would also lose the clarity added by the locality of the parameters within the request. In addition, when using a framework like JAX-RS, all the query parameters would show up within each resource handler, leading to potential conflicts and confusion.

如果您的查询只有一个级别",那么区别并不重要,两种类型的参数可以有效互换,但是,查询参数通常得到更好的支持和更广泛的认可.一般来说,我建议您坚持使用查询参数来处理 HTML 表单和简单的单级 HTTP API 等内容.

If your query has only one "level", then the difference is not really important and the two types of parameters are effectively interchangeable, however, query parameters are generally better supported and more widely recognized. In general, I would recommend that you stick with query parameters for things like HTML forms and simple, single-level HTTP APIs.

这篇关于URL 矩阵参数与查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 00:46