What's the difference between `:path-param` and `{path-param}` in Java Spark?

落花浮王杯 提交于 2019-12-12 15:28:34

问题


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}", () -> { ... } )

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?


回答1:


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

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

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

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.

Summary

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
  • Note that the returned value is always a String and you'll have to cast if needed.


来源:https://stackoverflow.com/questions/44301522/whats-the-difference-between-path-param-and-path-param-in-java-spark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!