Sangeeth S Kumar
Sangeeth S Kumar

Reputation: 142

Vaadin Flow Redirect to Specific Route on Page Reload

I am using Vaadin Flow. I am facing a problem that after I have navigated to a route and if I reload the page, i still land on the same page(Which is the way it should work I suppose). I wish to redirect to a specific route on reload. Something like capturing the reload event and redirecting to a specific route.

For Eg.

http://localhost:9090/user - The present route which I am presently at.

http://localhost:9090/ - The route to which I need to navigate on Reload of Page.

Thanks in Advance.

Upvotes: 3

Views: 2292

Answers (1)

schaphekar
schaphekar

Reputation: 495

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);
        }
    }
}

Upvotes: 3

Related Questions