Table of contents
1.
Introduction 📝 
2.
Defining Routes 🎯
2.1.
🔖Creating Route Aliases
3.
Navigating Between Routes ⚙️
3.1.
🔖Server-Side Navigation
3.2.
🔖Using the RouterLink Component
3.3.
🔖Using Standard Links
4.
Route Parameters 🌐
4.1.
🔖Defining Route Parameters
4.2.
🔖Alternatives to Route Parameters
5.
Frequently Asked Question❓
5.1.
What does route mean?
5.2.
What is the route parameter?
5.3.
How to define routes in Vaadin?
5.4.
What is RouterLink Component?
5.5.
How to open a link in a new tab?
6.
Conclusion ✉️
Last Updated: Mar 27, 2024
Medium

Defining Routes

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.

Defining Routes

Defining Routes 🎯

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

Example: Defining the Firstapp component as the default route target (empty route) for your application.

@Route("")
public class FirstApp extends Div {
    public FirstApp() {
        setText("First App");
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Example: Defining the SomePathComponent component as the target for the specific route "new/path

@Route("new/path")
public class NewPathComponent extends Div {
    public NewPathComponent() {
        setText("Welcome to New @Route!");
    }
}
You can also try this code with Online Java Compiler
Run Code

Assuming your application is running from the root context, the SomePathComponent component is displayed on the page when the user navigates to http://example.com/new/path, either by clicking a link in the application or typing the address in the address bar.

If the @Route annotation field is not used, the route target is generated from the class name. The derived name will be lowercase, with the trailing View removed. MainView and Main names will also be mapped to root (value will be "").

 

🔖Creating Route Aliases

You can also use @RouteAlias to construct route aliases. It is necessary to have a principal route generated using @Route. An alias for a route might have many names.

Example: Adding two @RouteAlias annotations for AppView. Navigating to "home" or "about" will navigate to the same view as the main route.

@Route("")
@RouteAlias("home")
@RouteAlias("about")
public class  AppView extends Div {
    public  AppView() {
        setText("welcome @Route!");
    }
}
You can also try this code with Online Java Compiler
Run Code

Navigating Between Routes ⚙️

Switching between routes/views may be done in two ways: programmatically with UI.navigate() methods or manually with links. The navigate() method is more flexible for a Java programmer since the view change may be given from anywhere in your code, and you can interact with the target view. On the other hand, links are the natural online method of going from one view to another, allowing you to share the direct link to a specific view with a colleague, for example, and they operate even after the session has ended.

🔖Server-Side Navigation

Various UI.navigate() methods can be called from server-side code to initiate navigation.

You should generally use the UI.navigate(Class? extends Component> navigationTarget) or navigate(Class? extends C> navigationTarget, RouteParameters parameters) methods, which take the target view's Class as an argument. When compared to String versions, this eliminates the need to manually build the route string.

The navigate() method in the browser causes a location update and the creation of a new history state record, but it does not cause a full page refresh.

Button button = new Button("Navigate to Home page");
button.addClickListener(e ->
     button.getUI().ifPresent(ui ->
           ui.navigate("homepage"))
);
You can also try this code with Online Java Compiler
Run Code

🔖Using the RouterLink Component

RouterLink is a component that uses the <a> tag to build links that point to route targets in your application.

Navigation using RouterLink retrieves the new component's content without refreshing the page. The page is changed in place rather than reloading the entire page, but the URL in the browser is updated.

Let’s understand RouterLink through an example:
 

void buildMenu() {
    menu.add(new RouterLink("Home", AppView.class));
}

@Route(value = "")
public class AppView extends Component {
}
You can also try this code with Online Java Compiler
Run Code

 

An illustration of this would be the use of RouterLink for navigation targets that include route parameters and whose navigation target class implements HasUrlParameter.

void buildMenu() {
    menu.add(new RouterLink("Welcome",
            GreetingComponent.class, "default"));
}


@Route(value = "greet")
public class GreetingComponent extends Div
        implements HasUrlParameter<String> {


    @Override
    public void setParameter(BeforeEvent event,
            String parameter) {
        setText(String.format("Welcome, %s!", parameter));
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Example: Using the Route template route with RouterLink as a navigation target.

void buildMenu() {
    menu.add(new RouterLink("Edit details of user",
            UserProfileEdit.class, new RouteParameters("userID", "1131")));
    menu.add(new RouterLink("Correct my details",
            UserProfileEdit.class));
}

@Route("user/:userID?/edit")
public class UserProfileEdit extends Div implements BeforeEnterObserver {
    private String userID;
    @Override
    public void beforeEnter(BeforeEnterEvent event) {
        userID = event.getRouteParameters().get("userID").
                orElse(CurrentUser.get().getUserID());
    }
}
You can also try this code with Online Java Compiler
Run Code

🔖Using Standard Links

It is also possible to navigate using regular <a href="home"> type links. You can accomplish this by using an Anchor component and providing an url and text content:

new Anchor("/app", "Go to /app route");
You can also try this code with Online Java Compiler
Run Code

 

Setting the anchor target property to _blank will cause a regular link to open in a new tab.

Anchor anchor = new Anchor("/app", "Go to /app route");
anchor.getElement().setAttribute("target", "_blank");
You can also try this code with Online Java Compiler
Run Code

 

By default, clicking on a regular link does not result in a full page reload since the Vaadin router intercepts all occurrences of anchor navigation. If you want a full page to reload to occur, for instance when accessing a page that is not Vaadin-implemented, you may add the router-ignore property; for instance,

<a router-ignore href="home">Go to the home page</a>. This can be done from the Java API as follows:
 

Anchor anchor = new Anchor("/app", "Go to /app route");
anchor.getElement().setAttribute("router-ignore", "");
You can also try this code with Online Java Compiler
Run Code

Route Parameters 🌐

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.

Users can access the appt route using the URL /app/<some-string>, for instance, if the application has a route with the name app that accepts a string parameter. For instance, visitors can call the welcome route using any of the following URLs:

  • /app/home
  • /app/about
  • /app/feature
  • and so on ..
     

In these examples, the home, about, and feature strings are route parameters that the app route can use to respond to requests.

🔖Defining Route Parameters

A view that takes route parameters supplied by the URL should:

  • a HasUrlParameter<T> implementation
     
  • Generics are used to define the parameter type
     

Based on values taken from the URL, HasUrlParameter specifies the setParameter() function that is invoked by the Router. Prior to the activation of a navigation target, this procedure is always called (before the BeforeEnter event).

As an illustration, consider creating a navigation target that uses a string argument to generate a welcome string, which it then uses as its own text content when navigating:

@Route(value = "app")
public class GreetingComponent extends Div
        implements HasUrlParameter<String> {


    @Override
    public void setParameter(BeforeEvent event, String parameter) {
        setText(String.format("welcome, %s!", parameter));
    }
}
You can also try this code with Online Java Compiler
Run Code

A separate navigation target with the exact @Route is specified to match app/<some particular path>. The navigation target is automatically established upon startup for every app/<anything> path. It is also important to remember that while resolving the URL, an exact navigation goal is always prioritized above route parameters.

🔖Alternatives to Route Parameters

The simplest way to accept parameters is via route parameters, which is the method discussed in this article. It should work for the majority of typical use cases. So, if at all feasible, it is advised to employ this strategy.

However, Vaadin Flow provides two more approaches for receiving parameters if utilizing route parameters is not acceptable for your use case:

  1. Query Arguments: This method works well when you need to accept a number of optional parameters or when you need to have explicit name-value pairs. (Refer to the Query Parameters manual.)
     
  2. Route Templates: This method of receiving parameters is the most effective but also the most difficult. It is advised against utilizing this strategy due to its complexity unless your particular use case cannot be satisfied by route or query parameters. (See the guide to Route Templates.)

Frequently Asked Question❓

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.

What is RouterLink Component?

RouterLink is a component that uses the <a> tag to build links that point to route targets in your application.

How to open a link in a new tab?

Setting the anchor target property to _blank will cause a regular link to open in a new tab.

Conclusion ✉️

In this article, we have extensively discussed how to define Routes and how to Navigating Between Routes along with Route parameters.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