Table of contents
1.
Introduction
2.
About Vaadin
3.
What is a Navigation Lifecycle?
4.
BeforeLeaveEvent
5.
Postponing a Navigation Transition
6.
BeforeEnterEvent 
7.
Rerouting
8.
Forwarding
9.
AfterNavigationEvent
10.
Frequently Asked Questions
10.1.
Is Vaadin still used?
10.2.
Is Vaadin a backend?
10.3.
Is Vaadin open source?
10.4.
Is Vaadin scalable?
10.5.
Is Vaadin stateless?
11.
Conclusion
Last Updated: Mar 27, 2024

Navigation Lifecycle

Author Amit Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Have you ever tried looking for something on Google, and it has taken you to a different website? 

title

This is called Navigation, or you can say you are navigating from one page to another page.

In this article, we will learn about Navigation Lifecycle in Vaadin in detail. We will also discuss the events in detail. We will also discuss some of the most important methods as well such as postpone, and reroute.

About Vaadin

vaadin

Vaadin is an open-source platform for Java that is used for the development of web applications. Vaadin consists of a Java web framework, a set of Web Components, and a set of tools that allows the developers to implement the modern web graphical user interfaces (GUI) using the programming language known as Java only (instead of HTML and JavaScript), TypeScript only, or a combination of two.

What is a Navigation Lifecycle?

map

The navigation lifecycle can be understood as a collection of events that are initiated when a user moves from one state to another or one view to another.

When a user switches from one state or view and another, a variety of events are fired, making up the navigation lifecycle. The UI instance's newly added listeners and any associated components that implement relevant observer interfaces get the events.

The Navigation LifeCycle consists of three events:

  • BeforeLeaveEvent
     
  • BeforeEnterEvent
     
  • AfterNavigationEvent
     

Let's study all these events one by one in detail.

BeforeLeaveEvent

now

The first event that is triggered during the navigation process is the BeforeLeaveEvent.

The event enables the navigation to be delayed, abandoned, or shifted to another location.

Before the navigation process begins, this event is sent to every instance of a component that implements BeforeLeaveObserver and is linked to the UI.

We can use the addBeforeLeaveListener(BeforeLeaveListener) method in the UI class so that we can make it feasible to add a standalone listener for this event.

Asking the users whether they want to save any unsaved changes before moving on to another section of the program is a typical use case for this event.

Postponing a Navigation Transition

postpone

BeforeLeaveEvent contains a method known as postpone(), which may be used for postponing the current navigational transition until a unique condition is met.

 

Example: Let us suppose that the client has requested the user’s confirmation before leaving the page:

public class SignupForm extends Div
        implements BeforeLeaveObserver {
    @Override
    public void beforeLeave(BeforeLeaveEvent testevent) {
        if (hasChanges()) {
            ContinueNavigationAction action =
                    testevent.postpone();
            ConfirmDialog testconfirmDialog = new ConfirmDialog();
                 testconfirmDialog.setText("Your form has changed! Are you sure about leaving?");
                 testconfirmDialog.setCancelable(true);
                 testconfirmDialog.addConfirmListener(__ -> action.proceed());
                 testconfirmDialog.open();
        }
    }

    private boolean hasChanges() {
      
        return true;
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Postponing causes an interruption to the process of notification to the observers and listeners. The following observers—those who arrived after the one who requested the postponement—are called when the transition begins again.

 

Example:

Assume that there are three observers for the current page: a, b, and c, who are notified in the same sequence.

  • The call to c and the rest of the transition procedure are postponed if b calls postpone().
     
  • If the transition is not continued, the notification of the event is never sent to c, and the transition is never completed.
     
  • A and B are not called once more, but c is informed if b executes the ContinueNavigationAction command to resume the transition.

BeforeEnterEvent 

wait

The second event that is triggered during the navigation process is the BeforeEnterEvent.

You can alter the navigation using the event to take you to a location other than the original one.

This event is often used to respond to unique circumstances, such as when there is no data to display or when the user does not have the necessary access rights.

Beginning with the UI and progressing through the child components, this event is sent to any component instance implementing BeforeEnterObserver that is related to the UI.

The event is triggered:

  • only after a Postpone method which is called during a BeforeLeaveEvent, has been resumed;
     
  • before detaching and reattaching components in order to make the UI match the place being navigated to.
     

Using the addBeforeEnterListener(BeforeEnterListener) method in the UI class, it is also feasible to add a separate listener for this event.

Rerouting

Both BeforeLeaveEvent and BeforeEnterEvent can be used to reroute dynamically.

map

Rerouting is often employed when it is necessary to display entirely different content in a specific condition.

After the call to the reroute() method:

  • Subsequent listeners or observers are not made aware of the event;
     
  • Events are fired based on a new navigation phase that is triggered by the method and is based on the new navigation target;
     
  • In the case of BeforeEnterEvent, the rerouting component's children are not initially created.
     

Example: Let’s try rerouting when entering a BlogList with no results.

@Route("no-items")
public class NoItemsView extends Div {
    public NoItemsView() {
        setText("No items found!");
    }
}

@Route("blog")
public class BlogList extends Div
        implements BeforeEnterObserver {
    @Override
    public void beforeEnter(BeforeEnterEvent event) {
        // implementation omitted
        Object testrecord = getItem();

        if (testrecord == null) {
            event.rerouteTo(NoItemsView.class);
        }
    }

    private Object getItem() {
       
        return null;
    }
}
You can also try this code with Online Java Compiler
Run Code

Forwarding

forward

The forwardTo() method is used for rerouting the navigation and also updating the browser URL.

BeforeEnter and BeforeLeave lifecycle stages allow for the use of forwarding to reroute to a different URL dynamically.

When the forwardTo() method is called:

  • The event is not triggered to any further observers or listeners;
     
  • The method then triggers a new navigation phase that is based on the new navigation destination and triggers new lifecycle events for the new forward navigation target;
     
  • For BeforeEnterEvent: the child components of the forwarding component are not even instantiated.
     

Example: Let’s try forwarding when viewing BlogList without the required permissions.

@Route("no-permission")
public class NoPermission extends Div {
    public NoPermission() {
        setText("Permission Denied!");
    }
}

@Route("blog-post")
public class BlogPost extends Div
        implements BeforeEnterObserver {
    @Override
    public void beforeEnter(BeforeEnterEvent event) {
        if (!hasPermission()) {
            event.forwardTo(NoPermission.class);
        }
    }

    private boolean hasPermission() {
        
        return false;
    }
}
You can also try this code with Online Java Compiler
Run Code

AfterNavigationEvent

destination

The third and last event triggered during the navigation process is the AfterNavigationEvent.

Following the completion of the actual navigation, this event is often utilized to update various UI elements. The content of a breadcrumb component can be changed, for instance, and the active menu item can be graphically designated as such.

AfterNavigationEvent is triggered:

  • after the BeforeEnterEvent, and
     
  • after updating which components are linked to the UI.
     

Further reroutes and similar adjustments are no longer feasible at this stage because the user is really presented with the current navigation status at this time.

After the navigation is finished, the event is sent to any associated component instance that implements AfterNavigationObserver.

Using the addAfterNavigationListener(AfterNavigationListener) method in the UI class, it is also feasible to add a standalone listener for this event.

 

Example: Let's try marking the active navigation element as active.

public class SideMenu extends Div
        implements AfterNavigationObserver {
    Anchor testblog = new Anchor("testblog", "Blog");


    @Override
    public void afterNavigation(
          AfterNavigationEvent event) {
        boolean active = event.getLocation()
                .getFirstSegment()
                .equals(testblog.getHref());
        testblog.getElement()
                .getClassList()
                .set("active", active);
    }
}
You can also try this code with Online Java Compiler
Run Code

Frequently Asked Questions

Is Vaadin still used?

Actually, Vaadin is the only framework that enables you to write UI 100% in Java. Vaadin is used by 150k developers worldwide and by 40% of Fortune-500 companies, according to its official source (vaadin.com).

Is Vaadin a backend?

Vaadin is an open-source platform that is used for building modern, collaborative web apps for Java backends. It integrates UI components, frameworks, and tools into one little web development stack.

Is Vaadin open source?

The core Vaadin framework, including most components, is free and open-source under the Apache 2.0 license.

Is Vaadin scalable?

In conclusion, yes, Vaadin applications do scale well. As with any framework, it's possible to make mistakes.

Is Vaadin stateless?

By default, Vaadin Fusion will not create server sessions and use the token-based authentication mechanism. The server then is stateless, allowing easier horizontal scaling of instances and high availability of services.

Conclusion

In this article, we have learned about Navigation Lifecycle in Vaadin in detail. We have also discussed the events in detail. We have also discussed some of the most important methods as well such as postpone, and reroute.

We hope that this article has provided you with the help to enhance your knowledge regarding Navigation Lifestyle in Vaadin and if you would like to learn more, check out our articles on Vaadin GridVaadin Board, and Vaadin Button.

Thanks

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available, Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Merry Learning!

Live masterclass