英文:
Vaadin Routing/Navigation
问题
以下是翻译好的内容:
所以我有一个 RequestHandler(使用 VaadinServiceInitListener):
public class ApplicationServiceInitListener implements VaadinServiceInitListener {
@Override
public void serviceInit(ServiceInitEvent event) {
event.addRequestHandler((session, request, response) -> {
...
});
}
}
在 RequestHandler 中,我想检查用户是否已登录。到目前为止都还好。
如果用户已登录,请求将像往常一样处理。如果没有登录,我想将他重定向到登录页面。请求处理程序能实现这个吗?
我使用了 UI 类的 navigate 方法,像这样:
UI.getCurrent().navigate("..");
但问题是在请求的时候,并没有实例化 UI,因此会得到一个 NPE。
英文:
So I have a RequestHandler (using the VaadinServiceInitListener):
public class ApplicationServiceInitListener implements VaadinServiceInitListener {
@Override
public void serviceInit(ServiceInitEvent event) {
event.addRequestHandler((session, request, response) -> {
...
});
}
And in the RequestHandler I want to check wether a user is logged in or not. So far so good.
If the user is logged in, the request will be treated usual. If not, I want to redirect him to the Login Page. Is that possible with the request Handler?
I used the navigate-Method of the UI class like this:
UI.getCurrent().navigate("..");
But the problem is that at the point of the request, there is no UI instantiated so I will get a NPE.
答案1
得分: 4
void beforeEnter(BeforeEnterEvent event) {
if (!LoginView.class.equals(event.getNavigationTarget()) && !SecurityUtils.isUserLoggedIn()) {
event.rerouteTo(LoginView.class);
}
}
<details>
<summary>英文:</summary>
Not the answer to your exact question (whether it could be done), but usually this goes into a `BeforeEnterListener` (where you can reroute), as documented in [routing lifecycle docs][1]. For an example see the code in the [spring security tutorial][2]:
```java
void beforeEnter(BeforeEnterEvent event) {
if (!LoginView.class.equals(event.getNavigationTarget()) && !SecurityUtils.isUserLoggedIn()) {
event.rerouteTo(LoginView.class);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论