在我的应用程序中,我想使用spark.Spark.before添加一个过滤器进行验证,如果请求被授予,那么我想向请求本身添加一些信息,所以在我的spark.Route实现中可以访问这个信息。
但我不知道该怎么做
例如:
// RequestFilter
before((request, response) -> {
if (isGrantedRequest()) {
// modify request adding params, etc
// maybe using some kind of RequestWrapper
}
})
.....
post("/", this::handle);
.....
// Request handler
Object handle(Request request, Response response) throws Exception {
// access to information added in request
}
答案 0 :(得分:1)
查看此answer。
您可以使用属性。与会话不同,这不会使您的应用程序状态完整。其他属性是请求的本地属性,与会话不同,它们对每个请求都具有唯一值,即使是同时请求也是如此。
在过滤器前设置属性。
14:30:04: Warning: componentWillMount is deprecated and will be removed in
the next major version. Use componentDidMount instead. As a temporary
workaround, you can rename to UNSAFE_componentWillMount.
Please update the following components: ExpoRootComponent,
RootErrorBoundary, Text, View
Learn more about this warning here:
xxx:/fb.me/react-async-component-lifecycle-hooks
- node_modules\react-native\Libraries\ReactNative\YellowBox.js:82:15 in warn
- node_modules\react-native\Libraries\Renderer\ReactNativeRenderer-
dev.js:5706:19 in printWarning
- ... 21 more stack frames from framework internals
14:30:06: Warning: componentWillReceiveProps is deprecated and will be
removed in the next major version. Use static getDerivedStateFromProps
instead.
Please update the following components: Text, View
Learn more about this warning here:
xxx:/fb.me/react-async-component-lifecycle-hooks
- node_modules\react-native\Libraries\ReactNative\YellowBox.js:82:15 in warn
- node_modules\react-native\Libraries\Renderer\ReactNativeRenderer-
dev.js:5706:19 in printWarning
- ... 21 more stack frames from framework internals
并在处理程序中阅读。
before((req, res) -> {
req.attribute("key", "value");
});
答案 1 :(得分:0)
您可以使用会话来实现此目的。它是用于设置数据的请求的一个位置。
在before
代码中,您将根据isGrantedRequest()
方法的结果创建会话并在其中设置一些属性:
Spark.before("/somePath", (req, res) -> {
Session ses = req.session(true);
if (isGrantedRequest()) {
ses.attribute("attr1", "valA");
ses.attribute("attr2", "valB");
} else {
ses.attribute("attr1", "valX");
ses.attribute("attr2", "valY");
}
});
在get
/ post
代码中,您将检索会话属性:
Spark.get("/somePath", (req, res) -> {
Session ses = req.session();
if (ses != null) {
String val1 = ses.attribute("attr1");
String val2 = ses.attribute("attr2");
System.out.println(val1 + " " + val2);
}
return "";
});
查看Spark's sessions API以查看更多选项。