Java Spark 中的 `:path-param` 和 `{path-param}` 有什么区别? [英] What's the difference between `:path-param` and `{path-param}` in Java Spark?

查看:56
本文介绍了Java Spark 中的 `:path-param` 和 `{path-param}` 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Java Spark 构建 REST 服务器,我想知道以下两种定义路径参数的语法之间的区别,使用 :path-parameter{路径参数}:

I'm working on a REST server built with Java Spark, and I was wondering about the difference between the following two syntaxes for defining path parameters, using :path-parameter vs {path-parameter}:

path("/containers/:container-id", () -> { ...} )

path("/shipments/{shipment-id}", () -> { ... } )

有一次,当查询路径/{handler-id}(嵌套在/v1/handlers中)上的路径参数时code>),我不得不将语法从 : 形式更改为 {} 形式,以使 Spark 在查询时不返回 nullhandler-id 的参数.

At one point, when querying the path parameters on the path /{handler-id} (which is nested inside /v1 and /handlers), I had to change the syntax from the : form to the {} form to get Spark to not return null when querying the parameters for handler-id.

那么这两种语法有什么区别?

So what's the difference between these two syntaxes?

推荐答案

在路径中定义参数的唯一语法是 :path-param.

The only syntax for defining a parameter in a path is :path-param.

查询这个参数的值是通过String paramVal = request.params(":path-param")(查询时冒号是可选的).

Querying the value of this parameter is done by String paramVal = request.params(":path-param") (the colon is optional when querying).

或者,如果您想获得包含所有参数名称-值的地图,您可以使用 request.params();

Or, if you want to get a map with all the parameters names-values you'll go request.params();

我不确定为什么您在查询参数时得到 null,但我猜您使用了 request.queryParams(":path-param");.但是这个API不是用来查询你想要的路径参数,而是查询一个查询参数,它们是路径形式的参数,比如/api/users?userId=1234.

I'm not sure about why you got null when querying your param, but I'm guessing you used request.queryParams(":path-param");. But this API is used not to query a path-params like you wanted, but to query a query params which are parameters in the form of path like /api/users?userId=1234.

总结

Path Definition  URL in browser                Query
---------------  ----------------------------  -----------------------------------
/api/users/:id   <host>/api/users/1234         request.params("id") ==> 1234
/api/users       <host>/api/users?id=1234      request.queryParams("id") ==> 1234

  • 请注意,返回值始终是 String,如果需要,您必须进行强制转换.
    • Note that the returned value is always a String and you'll have to cast if needed.
    • 这篇关于Java Spark 中的 `:path-param` 和 `{path-param}` 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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