Package org.jboss.elemento.router
The router module is built around a few simple concepts that work together to manage navigation, data loading, and DOM updates in your application.
Core Concepts
Place
A data class that represents a place in an application. A place is identified by a route (e.g., "/home" or
"/contacts/:contactId") and can have an optional title and a custom root element. Routes can have parameters such as
/contacts/:contactId, which will be parsed and made available to the page. Routes also support optional parameters using
the :param? syntax — for example, /users/:id? matches both /users and /users/123. Optional
parameters must be trailing. A place can also have a loader assigned to it for asynchronously loading data before the page is
displayed.
Places
A builder to set up multiple places in your application. It supports nested places, combining places from different sources, and assigning loaders to places. This makes it easy to structure complex routing hierarchies.
Page
A simple interface that represents a collection of HTML elements. Implementations should be cheap to create and need to implement
a single method: Iterable<HTMLElement> elements(Place, Parameter, LoadedData). Pages can also implement optional
attach() and detach() lifecycle methods for setup and cleanup.
LoadData
A functional interface to asynchronously load data before a page is created and added to the DOM. The function gets the place and
parameters as input, returns a promise of the data to be loaded, and is defined as
Promise<T> load(Place place, Parameter parameter). This is useful for fetching data from APIs or performing other async
operations before rendering.
PlaceManager
The main class of the router module. It performs several key tasks:
- Keeps track of registered places
- Handles navigation events (clicks on links, browser back/forward)
- Parses route parameters from URLs
- Calls loader functions to fetch data
- Updates the DOM with new page elements
- Manages browser history state
start() method to initialize routing and show
the initial page.
Optional Parameters
Routes can have optional parameters using the :param? syntax (trailing ?). Optional parameters must be at the
end of the route. A route like /users/:id? matches both /users and /users/123.
- Optional parameters use the
:name?syntax - Optional parameters must be trailing —
/users/:id?/editis invalid - Multiple trailing optional parameters are allowed:
/a/:b?/:c? - Required parameters can precede optional ones:
/a/:b/:c?
When an optional parameter is not present in the URL, Parameter.get(String) returns
null and Parameter.has(String) returns false. Use
Parameter.getOrDefault(String, String) for a fallback value.
@Route("/users/:id?")
public class UsersPage implements Page {
@Override
public Iterable<HTMLElement> elements(Place place, Parameter parameter, LoadedData data) {
if (parameter.has("id")) {
String id = parameter.get("id");
return asList(h(1, "User " + id).element());
} else {
return asList(h(1, "All Users").element());
}
}
}
URL Encoding
Route parameter values that contain special URL characters (/, ?, #, &, =, spaces)
are handled transparently by the router. There are two ways to work with encoded parameters:
Automatic encoding
Use the overloaded PlaceManager.goTo(String, String...),
PlaceManager.href(String, String...), and
Link.link(PlaceManager, String, String...) methods. Pass raw/decoded values — encoding is
handled internally:
// Navigate with encoded parameters
placeManager.goTo("/resource/:name", "my/file");
// Generate href with encoded parameters
String url = placeManager.href("/resource/:name", "my/file");
// Create a link with encoded parameters
Link.link(placeManager, "/resource/:name", "my/file");
Manual encoding
When building paths yourself for use with PlaceManager.goTo(String) or
PlaceManager.href(String), use the encoding utilities:
// Build an encoded path from a template
String path = Parameter.encodePath("/resource/:name", "my/file");
placeManager.goTo(path);
// Encode a single value
String encoded = Parameter.encode("my/file"); // → "my%2Ffile"
Reading parameters
Parameter.get(String) always returns decoded values. Use
Parameter.getRaw(String) for the raw/encoded form:
parameter.get("name") // → "my/file" (decoded)
parameter.getRaw("name") // → "my%2Ffile" (encoded)
Annotations
To simplify the creation of Place instances in large applications, the router module provides
annotation-based configuration using an annotation processor:
Route
Marks a Page implementation as a routable place. The annotation requires a route value and can
include optional attributes for title, root selector, and a reference to a named loader. If the annotated page class has exactly
one public static method that returns LoadData<?> and accepts no parameters, it will automatically be used as the loader
for that place.
Loader
Marks a class or public static method as a named loader. If used on a class, the class must implement LoadData<T>. If
used on a static method, the method must return LoadData<?> and not accept any parameters. Named loaders can be
referenced by the loader attribute of the @Route annotation.
Example Usage
Here's a complete example showing how to set up routing with data loading and nested routes:
@Route("/time/:area/:location")
public class TimePage implements Page {
// This method is automatically used as the loader for the place
public static LoadData<String> loadTime() {
return (place, parameter) -> {
String area = parameter.get("area");
String location = parameter.get("location");
String url = "https://worldtimeapi.org/api/timezone/" + area + "/" + location;
return fetch(url)
.then(Response::json)
.then(json -> {
JsPropertyMap<String> map = Js.cast(json);
return Promise.resolve(map.get("datetime"));
});
};
}
@Override
public Iterable<HTMLElement> elements(Place place, Parameter parameter, LoadedData data) {
String area = parameter.get("area");
String location = parameter.get("location");
String currentTime = data.get();
return asList(
h(1, "Current time").element(),
p()
.add("It's ")
.add(span().text(currentTime))
.add(" in " + area + "/" + location)
.element());
}
}
@Route(value = "/", title = "Home")
public class HomePage implements Page {
@Override
public Iterable<HTMLElement> elements(Place place, Parameter parameter, LoadedData data) {
return asList(
h(1, "Welcome").element(),
p()
.add("What time is it in ")
.add(a("/time/Europe/Berlin").textNode("Berlin"))
.add("?")
.element());
}
}
public class Application {
public void entryPoint() {
body().add(div().id("main"));
Places allPlaces = places()
.add(new AnnotatedPlaces()) // generated places instance
.add(place("/foo"), FooPage::new)
.add(place("/bar"), BarPage::new)
.children("/level1", places()
.add(place("/"), Level1Page::new) // index page
.add(places() // siblings
.add(place("/foo"), Foo1Page::new)
.add(place("/bar"), Bar1Page::new))
.children("/level2", places()
.add(place("/foo"), Foo2Page::new)
.add(place("/bar"), Bar2Page::new)));
PlaceManager placeManager = new PlaceManager()
.root(By.id("main"))
.register(allPlaces);
placeManager.start();
}
}
Additional Features
The router module provides several additional features for advanced use cases:
- Before/After handlers: Execute code before or after a place transition using
BeforePlaceHandlerandAfterPlaceHandler - Custom error pages: Define custom pages for 404 (not found), data loading errors, and other error conditions
- Base paths: Support for applications served from subdirectories
- Link selection: Control which links are managed by the router using CSS selectors
- Custom root elements: Each place can render into a different root element
- See Also:
-
ClassDescriptionAn interface that represents a handler for performing actions after a place is changed.This functional interface represents a handler that is executed before a place transition occurs.The Link class represents a hyperlink element that creates hyperlinks using the
PlaceManager.LoadData<T>Functional interface representing a loader function that loads data for a given place.The LoadedData class represents data loaded by a loader.A page interface represents a collection of HTML elements.The Parameter class is used to represent parameters and their values in a route path.Represents a place in an application.The place manager is the central part of the router.Represents a collection of places in an application.This class is an annotation that can be used to decorate classes with routing information.