Vaadin 路由/导航

huangapple go评论91阅读模式
英文:

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()) &amp;&amp; !SecurityUtils.isUserLoggedIn()) {
		event.rerouteTo(LoginView.class);
	}
}

huangapple
  • 本文由 发表于 2020年10月21日 23:35:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64467014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定