如何解析喷雾路由中的获取请求参数? [英] How can I parse out get request parameters in spray-routing?
问题描述
这是代码段的样子
get{
respondWithMediaType(MediaTypes.`application/json`){
entity(as[HttpRequest]){
obj => complete{
println(obj)
"ok"
}
}
}
}~
我可以将请求映射到spray.http.HttpRequest对象,并且可以从该对象中提取uri,但我想与手动执行操作相比,解析请求中的参数要容易得多。
I can map the request to a spray.http.HttpRequest object and I can extract the uri from this object but I imagine there is an easier way to parse out the parameters in a get request than doing it manually.
例如,如果我的get请求为
For example if my get request is
http://localhost:8080/url?id=23434&age=24
我希望能够从此请求中获取ID和年龄
I want to be able to get id and age out of this request
推荐答案
实际上,您可以做得更好。在路由中有两个指令: parameter
和 parameters
,我想区别很明显,您也可以使用一些修饰符:!
和?
。如果是!
,则意味着必须提供此参数,否则将拒绝请求,并返回?
选项,因此您可以在这种情况下提供默认参数。示例:
Actually you can do this much much better. In routing there are two directives: parameter
and parameters
, I guess the difference is clear, you can also use some modifiers: !
and ?
. In case of !
, it means that this parameter must be provided or the request is going to be rejected and ?
returns an option, so you can provide a default parameter in this case. Example:
val route: Route = {
(path("search") & get) {
parameter("q"!) { query =>
....
}
}
}
val route: Route = {
(path("search") & get) {
parameters("q"!, "filter" ? "all") { (query, filter) =>
...
}
}
}
这篇关于如何解析喷雾路由中的获取请求参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!