Your question is not very clear whether you just want
a) alias or
b) to create a view that is shown only once and after that redirects the user else where.
For alias there is a very simple solution of using @RouteAlias
annotation. This makes possible to add multiple routes to the view.
@Route(value = "", layout = MainLayout.class)
@RouteAlias(value = "main", layout = MainLayout.class)
public class MainView extends VerticalLayout {
...
}
For the second case I would look into BeforeEnterEvent
, which is fired during navigation and facilitates redirection (see: https://vaadin.com/docs/v14/flow/routing/tutorial-routing-lifecycle). You will need also @PreserveOnRefresh
, since otherwise new instance of view will be created and count will be always zero.
@PreserveOnRefresh
@Route(value = "", layout = MainLayout.class)
public class MainView extends VerticalLayout implements BeforeEnterObserver {
private int count = 0;
@Override
public void beforeEnter(BeforeEnterEvent event) {
if (count > 0) {
event.forwardTo(OtherView.class);
}
count++;
}
}
If you would rather restricts navigation to that view, so that it can only happen through your application and not by direct link (or refresh), then you can accomplish that with a BeforeEnterObserver
and checking the NavigationTrigger
.
It will be PAGE_LOAD
when navigating directly by URL or when refreshing the browser tab, ROUTER_LINK
when using a RouterLink
and UI_NAVIGATE
when using UI#navigate
.
Note that a user can create a router link in the browser even if you haven't created one, so you shouldn't rely on that for security.
@Route
public class ExampleView extends VerticalLayout implements BeforeEnterObserver {
public ExampleView() {
add("Hello");
}
@Override
public void beforeEnter(BeforeEnterEvent beforeEnterEvent) {
if (beforeEnterEvent.getTrigger() == NavigationTrigger.PAGE_LOAD) {
beforeEnterEvent.rerouteTo(MainView.class);
}
}
}