Work in progress
Routing and URL Parameters
URL Parameters for Navigation Targets
A navigation target that supports parameters passed through the URL should implement the HasUrlParameter
interface and define the parameter type using generics. In this way, the Router API can offer a type-safe way of constructing URLs that lead to a specific target.
HasUrlParameter
defines the setParameter method that is invoked by Router based on values extracted from the URL. The method will always be invoked before a navigation target is activated.
In the following code snippet we define 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.
Java
@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 this navigation target will automatically be configured to every path of the form greet/<anything>, except in the case where a separate navigation target with an exact @Route
has been configured to match greet/<some specific path> the exact navigation target takes precedence when resolving the URL.
Optional URL parameters for Navigation Targets
URL parameters can be annotated using @OptionalParameter
to have the route match both greet and greet/<anything>.
Java
@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 | Also with an optional parameter a specific route will have precedence over the parameterised one. |
Wildcard URL parameters for Navigation Targets
In cases where more parameters are wanted the URL parameter can also be annotated with @WildcardParameter
to have the route match greet and anything after for instance greet/one/five/three
Java
@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 parameter for Wildcard parameter will never be null . |
Note | More specific paths will have precedence over the wildcard target. |