Typed URL Parameters for Navigation Targets
A navigation target that supports typed parameters passed through the URL should:
implement the HasUrlParameter interface, and
define the parameter type using generics.
HasUrlParameter defines the setParameter() method that is called by the Router, based on values extracted from the URL.
This method will always be invoked before a navigation target is activated (before the BeforeEnter
event).
Example: Defining a navigation target that takes a string parameter and produces a greeting string from it, which the target then sets as its own text content on navigation:
@Route(value = "greet")
public class GreetingComponent extends Div
implements HasUrlParameter<String> {
@Override
public void setParameter(BeforeEvent event, String parameter) {
setText(String.format("Hello, %s!", parameter));
}
}
On startup, the navigation target is automatically configured for every
greet/<anything>
path, except where a separate navigation target with the exact@Route
is configured to matchgreet/<some specific path>
.
Note | An exact navigation target always takes precedence when resolving the URL. |
Note |
The URL defined in the @Route annotation must not include the parameter template placeholder.
It is automatically added internally to the URL template.
|
Optional URL Parameters
URL parameters can be annotated as optional using @OptionalParameter
.
Example: Defining the route to match both greet
and greet/<anything>
:
@Route("greet")
public class OptionalGreeting extends Div
implements HasUrlParameter<String> {
@Override
public void setParameter(BeforeEvent event,
@OptionalParameter String parameter) {
if (parameter == null) {
setText("Welcome anonymous.");
} else {
setText(String.format("Welcome %s.", parameter));
}
}
}
Note | A more specific route always takes precedence over a parameterized route. |
Wildcard URL Parameters
When more parameters are needed, the URL parameter can also be annotated with @WildcardParameter
.
Example: Defining the route to match greet
and anything after it, for instance greet/one/five/three
:
@Route("greet")
public class WildcardGreeting extends Div
implements HasUrlParameter<String> {
@Override
public void setParameter(BeforeEvent event,
@WildcardParameter String parameter) {
if (parameter.isEmpty()) {
setText("Welcome anonymous.");
} else {
setText(String.format("Handling parameter %s.", parameter));
}
}
}
Note |
The wildcard parameter will never be null .
|
Note | More specific routes always take precedence over wildcard routes. |