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

  1. @Route(value = "greet")
  2. public class GreetingComponent extends Div
  3. implements HasUrlParameter<String> {
  4. @Override
  5. public void setParameter(BeforeEvent event, String parameter) {
  6. setText(String.format("Hello, %s!", parameter));
  7. }
  8. }

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

  1. @Route("greet")
  2. public class OptionalGreeting extends Div
  3. implements HasUrlParameter<String> {
  4. @Override
  5. public void setParameter(BeforeEvent event,
  6. @OptionalParameter String parameter) {
  7. if (parameter == null) {
  8. setText("Welcome anonymous.");
  9. } else {
  10. setText(String.format("Welcome %s.", parameter));
  11. }
  12. }
  13. }
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

  1. @Route("greet")
  2. public class WildcardGreeting extends Div
  3. implements HasUrlParameter<String> {
  4. @Override
  5. public void setParameter(BeforeEvent event,
  6. @WildcardParameter String parameter) {
  7. if (parameter.isEmpty()) {
  8. setText("Welcome anonymous.");
  9. } else {
  10. setText(String.format("Handling parameter %s.", parameter));
  11. }
  12. }
  13. }
Note
The parameter for Wildcard parameter will never be null.
Note
More specific paths will have precedence over the wildcard target.