问题
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
Stringand you'll have to cast if needed.
来源:https://stackoverflow.com/questions/44301522/whats-the-difference-between-path-param-and-path-param-in-java-spark