Table of contents
1.
Introduction 📝 
2.
Registering Routes Dynamically
2.1.
🔖Configuring User-Specific Routes
2.2.
🔖Removing Routes
2.3.
🔖Adding Routes on Application Startup
2.4.
🔖Getting Registered Routes and Listening for Changes
2.5.
🔖Adding Route Aliases for Dynamic Routes
2.6.
🔖Dynamic Registration of @Route Annotated Classes
3.
Frequently Asked Question❓
3.1.
How can we register routes dynamically?
3.2.
What does route mean?
3.3.
What is the route parameter?
3.4.
How to define routes in Vaadin?
3.5.
How to remove the admin route in vaadin?
4.
Conclusion ✉️
Last Updated: Mar 27, 2024

Registering Routes Dynamically

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

Introduction 📝 

The router compares the current URL to the established routes when you launch your application. The routes, in turn, are in charge of displaying templates, loading data, and configuring the application state. In this article, we will discuss how to define Routes and how to Navigating Between Routes along with Route parameters.

Registering Routes Dynamically

Registering Routes Dynamically

You may add and remove routes dynamically at runtime in addition to registering routes and route templates using the @Route annotation. This is helpful, for instance, when a route needs to be added or withdrawn due to modified business data or starting program setup.

You may restrict route access using the RouteConfiguration class to:

  • the whole user base of the program, or
     
  • only a select few users are actively using the session scope.
     

The static methods forSesionScope() and forApplicationScope() from the RouteConfiguration class allow you to access the scope.

🔖Configuring User-Specific Routes

You can configure user-specific routes by adding and removing routes for certain users; for example, based on their access rights.

RouteConfiguration.forSessionScope()
        .setRoute(
                "admin", 
                AdminView.class 
         );


RouteConfiguration.forSessionScope()
        .setRoute(
                "home", 
                HomeView.class, 
                MainLayout.class 
        );
You can also try this code with Online Java Compiler
Run Code


A unique user's session scope can override any registered @Route in the application scope.

Only while the session is active can the current user access the routes in the session scope. The session-scoped routes are no longer accessible when the user logs out, invalidating the session. There is no need to delete these routes manually.

🔖Removing Routes

Just like we had added some permission to users we can also remove them. You must specify precisely which route to delete when eliminating routes.

Example:

1. Removing a navigation target (AdminView.class) along with all of its registered route aliases and route templates. 

RouteConfiguration configuration = RouteConfiguration
        .forSessionScope();
configuration.removeRoute(AdminView.class);
You can also try this code with Online Java Compiler
Run Code

 

2. Removing a path ("admin"), which only removes the target mapped to it.

configuration.removeRoute("admin");
You can also try this code with Online Java Compiler
Run Code


Remarks:

  • The application-scoped route becomes accessible once more once a route in the session scope that had previously replaced a route in the application scope is removed.
  • Any class annotations are disregarded when dynamically registering a route, with the exception of methods that contain Annotated, like setAnnotatedRoute()
     

For further related information, see:

🔖Adding Routes on Application Startup

In the above section, we see how to add and remove the routes. Now let's try to Adding Routes to Application Startup

Example: Registering a route while deploying using ServiceInitLister.

public class ApplicationServiceInitListener
        implements VaadinServiceInitListener {


    @Override
    public void serviceInit(ServiceInitEvent event) {
               if (!event.getSource()
                .getDeploymentConfiguration()
                .isProductionMode()) {
            RouteConfiguration configuration =
               RouteConfiguration.forApplicationScope();


            configuration.setRoute(
                "crud", 
                DBCrudView.class 
            );
        }
    }
}
You can also try this code with Online Java Compiler
Run Code

🔖Getting Registered Routes and Listening for Changes

You might need to change UI elements, including navigation menus, based on the added or withdrawn routes when routes are registered dynamically.

The getAvailableRoutes() function of the RouteConfiguration allows you to get the registered route templates. Using the addRoutesChangeListener() function, you can set up a listener to receive notifications of route changes.

Example: Obtaining available routes and registering routes switch listeners.

RouteConfiguration configuration = RouteConfiguration
        .forSessionScope();
configuration.getAvailableRoutes()
        .forEach(menu::addMenuItem);


configuration.addRoutesChangeListener(event -> {
      event.getAddedRoutes().stream()
            .filter(route -> route instanceof RouteData)
            .forEach(menu::addMenuItem);
    event.getRemovedRoutes().stream()
            .filter(route -> route instanceof RouteData)
            .forEach(menu::removeMenuItem);
});
You can also try this code with Online Java Compiler
Run Code

🔖Adding Route Aliases for Dynamic Routes

For adding dynamic routes, the first route for which a navigation target is added is designated as the primary route, which can be obtained using the RouteConfiguration getUrl() methods.

A route alias is any additional registered route.

RouteConfiguration configuration =
        RouteConfiguration.forSessionScope();
configuration.setRoute("main", MyRoute.class);
configuration.setRoute("info", MyRoute.class);
configuration.setRoute("version", MyRoute.class);
You can also try this code with Online Java Compiler
Run Code


The configuration.getUrl(MyRoute.class) function returns main in this case.

Example: The previous route registration example's static class definition is equivalent.

@Route("main")
@RouteAlias("info")
@RouteAlias("version")
private class MyRoute extends Div {
}
You can also try this code with Online Java Compiler
Run Code


If the "primary" path is eliminated but an alias path remains, the first alias in the register becomes the main path.

🔖Dynamic Registration of @Route Annotated Classes

You may configure the routes statically but postpone registration until runtime if you wish to map all routes, in a similar manner, using the @Route annotation.

Add the registerAtStartup = false argument to the @Route annotation to bypass static registration to the application-scoped registry on startup. This also makes it easy to leverage existing parent chains and change pathways from the parent.

Example: To postpone route registration, use the registerAtStartup argument.

@Route(value = "quarterly-report",
       layout = MainLayout.class,
       registerAtStartup = false)
@RouteAlias(value = "qr", layout = MainLayout.class)
public class ReportView extends VerticalLayout
        implements HasUrlParameter<String> {
}


if (getCurrentUser().hasAccessToReporting()) {
    RouteConfiguration.forSessionScope()
            .setAnnotatedRoute(ReportView.class);
}
You can also try this code with Online Java Compiler
Run Code


In the above example, we had seen the use of the registerAtStartup argument. You can also see the example of a sample project by clicking here  Adding a New View on User Log-in.

Frequently Asked Question❓

How can we register routes dynamically?

You may add and remove routes dynamically at runtime in addition to registering routes and route templates using the @Route annotation.

What does route mean?

The route generally means the path, which decides the way data is sent from source to destination.

What is the route parameter?

The variable components of a URL segment are referred to as route parameters. These parameters offer a mechanism to transmit additional data to a certain route.

How to define routes in Vaadin?

The @Route annotation may be used to specify any component as a route target for a specific URL fragment.

How to remove the admin route in vaadin?

To remove the admin route in Vaadin we have to use the following code configuration.removeRoute("admin");.

Conclusion ✉️

In this article, we have extensively discussed how to register Routes Dynamically and how to remove and add the routes. We will also discuss the configuration of user-specific routes. If you would like to learn more, check out our articles on

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. 

Enroll 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.

Conclusion Image

Do upvote our blog to help other ninjas grow. 

Happy Coding!

Live masterclass