Application
Every Nalu application needs one application interface. The application interface defines the basic behavior of Nalu.
Application interface
To implement Nalu in your application, first create an application interface:
@Application(loader = MyLoader.class,
startRoute = "/application/search",
context = MyApplicationContext.class)
interface MyApplication
extends IsApplication {
}
The application interface must extend IsApplication and needs the @Application annotation.
The attributes of the Application annotation are:
- startRoute: The start route is the initial route that is called in case the application is called without a hash. If the application is called with a hash, the startRoute-attribute has no effect.
- loader: the application loader will be executed at application start and before loading the modules. (see: Application Loader). This attribute is optional.
- postLoader: the application post loader will be executed at application start and after all modules have been added and all module loaders have been executed. (see: Application Loader). This attribute is optional.
- context: the application context is a singleton that will be injected in every filter, controller and handler of the application (see: Context).
- isUsingHistory: if true Nalu supports history, so the application can reload. Otherwise, no hash will be created and the url stays untouched. This might be useful, in case the application should never reload or will be used embedded inside another web site. (default: true)
- usingHash: if true Nalu uses a hash token, otherwise a hash-less token (Clean URLs). (default: true)
- routingMode:
RoutingMode.HASHorRoutingMode.CLEAN_URL(hash-less, Clean URLs).CLEAN_URLhas the same effect asusingHash = false(default: HASH) - basePath: part of the URL in front of the routes (f.e.
/myapp), only used withRoutingMode.CLEAN_URL(default: empty) - usingUnderscoreForParametersInUrl: if true Nalu uses a '_' before a parameter inside the url (default: false)
- stayOnSite: if true Nalu will - in case of an empty hash - add a new history entry using the hash of the start route
- alertPresenter: Tells Nalu to use a custom alert - this parameter is optional
- confirmPresenter: Tells Nalu to use a custom confirm - this parameter is optional
- illegalRouteTarget: Tells Nalu to use this route instead showing an error message - this parameter is optional
- usingBaseHref: if true Nalu detects and sets the base href for the application. This is especially useful if hash-less routing (Clean URLs) is activated and the resources (images, documents etc.) are linked relative (default: false)
- usingTrailingSlash: if true the hash will end with an '/'. if false there will be no trailing slash at the end of the hash (default: false)
Clean URLs (Hash-less Routing) (since v4.0.0)
Clean URLs (also called hash-less routing) give your application readable, bookmarkable URLs without the hash symbol (#). Nalu uses the browser History API (pushState / replaceState / popstate) for that.
| Approach | Example URL | Pros | Cons |
|---|---|---|---|
| Hash-based | http://localhost:8080/index.html#/app/route | No server config needed | Not SEO-friendly |
| Clean URL | http://localhost:8080/app/route | SEO, bookmarks, readable | Needs a fallback on the server (see below) |
Why does the server need a fallback?
The part behind the # is never sent to the server. With a hash-based URL a reload always requests index.html, and Nalu resolves the route itself.
With a clean URL the browser requests the whole path (f.e. /app/route) from the server on every reload or deep link. There is no such file, so the server answers with a 404. The server has to answer every path that belongs to your application with the index.html of the application. Nalu then reads the route from the path. This is the same for every single-page framework (f.e. Angular's default PathLocationStrategy). Only the hash-based variant works without server configuration.
How to enable Clean URLs in Nalu
Use one switch in the @Application annotation:
@Application(startRoute = "/shell/home",
context = MyContext.class,
routingMode = RoutingMode.CLEAN_URL)
public interface MyApplication
extends IsApplication {
}
If the application is not served from the root of the host, set the basePath:
@Application(startRoute = "/shell/home",
context = MyContext.class,
routingMode = RoutingMode.CLEAN_URL,
basePath = "/myapp")
| Attribute | Meaning | Default |
|---|---|---|
routingMode | HASH (/index.html#/shell/route) or CLEAN_URL (/myapp/shell/route) | HASH |
basePath | Part of the URL in front of the routes, f.e. /myapp. Leading / trailing slashes are normalized. Only used with CLEAN_URL. | empty |
usingHash = false still works and has the same effect as routingMode = RoutingMode.CLEAN_URL. If you do not set a basePath, Nalu guesses the context path from the URL (everything in front of the first shell route). We recommend to set basePath explicitly.
Optional settings that fit to Clean URLs:
usingBaseHref = true: Nalu sets the<base href>so relative resources (images, CSS, ...) are resolved against thebasePath. Alternatively use absolute paths for all resources (/myapp/img/logo.png) and a<base href="/myapp/">in yourindex.html.usingTrailingSlash = true: routes end with/(/myapp/shell/route/).
Note: You do not need to register another plugin. The default core plugin handles clean URL routing. Register
CleanUrlWithParameterHandlingCoreWebPlugin(NaluCorePluginFactory.INSTANCE.registerPlugin(...)beforerun()) only if you want Nalu to keep URL query parameters (?a=b) of the start URL when routing.
Fluent configuration (alternative to the annotation)
The same settings can be made in code, f.e. to read them from an environment-specific source. Values set with NaluApp.configure() override the values of the @Application annotation, everything that is not set keeps the annotation value:
NaluApp.configure()
.routing(RoutingMode.CLEAN_URL)
.basePath("/myapp")
.startRoute("/shell/home")
.usingBaseHref(true)
.usingTrailingSlash(false)
.start(new MyApplicationImpl(),
new NaluPluginElemental2());
start(application, plugin) applies the configuration and calls application.run(plugin). If you start the application yourself, call .apply() before run(plugin).
Links
Plain <a href="/myapp/shell/route"> links make the browser reload the page. To route inside the application without a reload, mark the link with data-nalu-link:
<!-- uses the path of the href -->
<a data-nalu-link href="/myapp/shell/route">Route</a>
<!-- uses the value of the attribute as route -->
<a data-nalu-link="/shell/route" href="/myapp/shell/route">Route</a>
Clicks with Ctrl / Cmd / Shift / Alt, other mouse buttons, links to other origins and links with a target other than _self are left to the browser. Query parameters of the link are not evaluated.
Server configuration
Every path of the application must be answered with index.html. Real files (JavaScript, CSS, images) must still be delivered as they are. The examples assume the application lives under /myapp/.
nginx
location /myapp/ {
root /var/www;
try_files $uri $uri/ /myapp/index.html;
}
Apache (.htaccess inside the application directory)
FallbackResource /myapp/index.html
Alternative with mod_rewrite:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /myapp/index.html [L]
Spring Boot
Forward the application routes to index.html. List the shells of your application (the first part of each route):
@Controller
public class ClientRoutesController {
@GetMapping({"/myapp", "/myapp/", "/myapp/login/**", "/myapp/app/**"})
public String forward() {
return "forward:/myapp/index.html";
}
}
Node.js (Express)
app.use('/myapp', express.static('dist'));
app.get('/myapp/*', (req, res) => res.sendFile(path.join(__dirname, 'dist', 'index.html')));
Tomcat (and other servlet containers)
The application is deployed as myapp.war, so it is served under the context path /myapp (matches basePath = "/myapp"). A servlet filter forwards every request that is not a real file of the web application to index.html:
@WebFilter("/*")
public class SpaFallbackFilter
implements Filter {
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String path = httpRequest.getRequestURI()
.substring(httpRequest.getContextPath()
.length());
// real file or directory of the web application (js, css, images, index.html, ...)?
if (httpRequest.getServletContext()
.getResource(path) != null) {
chain.doFilter(request,
response);
} else {
// an application route: let the browser load the application
request.getRequestDispatcher("/index.html")
.forward(request,
response);
}
}
}
Use jakarta.servlet.* for Tomcat 10 and newer and javax.servlet.* for Tomcat 9 and older. The same filter works for Jetty and other servlet containers. Instead of @WebFilter you can register the filter in the web.xml.
A simpler alternative is an error page in the web.xml. It also works for development, but the server still answers with the status 404, which is bad for search engines and monitoring:
<error-page>
<error-code>404</error-code>
<location>/index.html</location>
</error-page>
Development server
GWT SuperDevMode and most dev servers (f.e. webpack-dev-server with historyApiFallback, Vite) need the same fallback. Configure it in your dev server, otherwise a reload on a deep link ends in a 404.
Legacy: the ?uri= redirect
Earlier versions required the server to redirect unknown paths to index.html?uri=/shell/route. This is not needed anymore: Nalu reads the route directly from location.pathname. Existing servers that still redirect with ?uri= keep working, because the parameter is used as the start route if present.
Troubleshooting
- 404 on reload or deep link: the server does not fall back to
index.html(see above). - Blank page, JavaScript/CSS cannot be loaded on a deep link: the resources are linked relative (
js/app.js). Use absolute paths, a<base href>orusingBaseHref = true. - Routes are wrong behind a reverse proxy or in a sub directory: set
basePathexplicitly.
Start Route
The start route is the route, that will be used in case the application is called without a hash or URI.
Minimal requirements for a start route are:
- needs a shell
- needs a part to identify a controller
Important note: a start route can not have a parameter!
Using only a shell as a start route will produce an error.
Custom alert and confirm
Nalu offers the possibility to add a custom alert and confirm dialog. In case it is set, Nalu will use the custom dialog instead of the default dialog from the plugin.
A custom alert needs to implement the IsCustomAlertPresenter and a custom confirm dialog needs to implement the IsCustomConfirmPresenter.
Filter Annotation
Nalu allows you to use filters to stop routings in order to interrupt a route before it is handled. In case a route is interrupted, you can redirect to another route.
To create a filter, add the @Filter-annotation to the application interface.
Nalu supports the use of more than one filter.
Creating Filters
To create a filter, you need to:
- implement the
IsFilter-interface - override the
filter-method: this method enables you to stop a routing. If filterEvent method returns false, the route is stopped, otherwise, it is forwarded to the router. - override the
redirect-method: in case the routing is stopped, the route returns the new route to go to. - override the
parameters-method: the parameters of the route. In case there are no parameters, returnString[]{}.
Nalu will inject the context into a filter.
Example of a filter:
import java.util.Objects;
public class MyFilter
extends AbstractFilter<MyContext> {
@Override
public boolean filter(String route,
String... params) {
// checking f.e. a route
if ("/myShell/myRoute01".equals(route)) {
// interrupt routing
return false;
}
// checking for example a parameter
if (params.length > 0) {
if ("Bart".equals(params[0])) {
// interrupt routing
return false;
}
}
// routing ok!
return true;
}
@Override
public String redirectTo() {
return "/redirectShell/redirectRoute";
}
@Override
public String[] parameters() {
return new String[] {};
}
}
Adding Filters
Once you have created a filter, you need to tell Nalu that there is at least one filter and that Nalu has to use it. This can be done thanks to the @Filters-annotation, which can be used on your application interface.
@Filters(filterClasses = { MyFilter01.class, MyFilter02.class })
interface MyApplication
extends IsApplication {
}
The @Filters annotation will only be handled if the interface is annotated with @Application!
The annotation @Filters has the following attributes:
- filterClasses: set one or several filters to use. An instance will be created for each class specified.
In case you have more than one filter, filters will be executed in an unconditional order!
Logger Annotation (since version v2.1.0)
Nalu has a logger feature to log information to the browser console or to the server (service needs to be provided).
To activate the log feature, you need to annotate your application class with @Logger:
@Logger(clientLogger = DefaultElemental2ClientLogger.class,
logger = MyLogger.class)
interface MyApplication
extends IsApplication {
}
The @Logger annotation will only be handled if the interface is also annotated with @Application!
@logger-annotation has the following attributes:
- clientLogger: defines the class of the client side logger to use depending on the selected plugin
- logger: defines the class of the logger which can be used to send log messages to the server
Every plugin provides a default client logger. In case you do not want to create an own logger, use:
- gwt-plugin-elemental2:
DefaultElemental2Logger.class - gwt-plugin-elemento:
DefaultElementoLogger.class - gwt-plugin-gwt:
DefaultGWTLogger.class
The logger needs to implement the IsLogger-interface and looks like this:
public class MyLogger
extends AbstractLogger<MyContext> {
@Override
public void log(List<String> messages,
boolean sdmOnly) {
LoggingServiceFactory.INSTANCE.log(messages)
.onSuccess(response -> {
})
.onFailed(failed -> {
})
.send();
}
}
This example uses Domino-rest to send the messages to server.
A log message can be triggered by firing a LogEvent.
Version and Build Time
Nalu supports setting a version String using an annotation and storing the build time. To get this feature, the context needs to extend AbstractModuleContext and inside the application interface you have to add the Version-annotation.
@Application(loader = MyLoader.class,
startRoute = "/application/search",
context = MyApplicationContext.class)
@Version("1.0.1")
interface MyApplication
extends IsApplication {
}
The example above will set the version of the application to '1.0.1'. To access the application version, use: context.getApplicationVersion(). To access the build time call context.getApplicationBuildTime().
Important:
To access the build time, your context need to extend the AbstractModuleContext-class.
It is possible to override the value from the version annotation from the command line. Nalu will look for a property called "nalu.application.version". If the property exists, Nalu will use this value. This will only work, in case the Version annotation is used.
The following set up inside the client pom (in a multi module project) will provide the maven project version to Nalu:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<goals>
<goal>set-system-properties</goal>
</goals>
<configuration>
<properties>
<property>
<name>nalu.application.version</name>
<value>${project.version}</value>
</property>
</properties>
</configuration>
</execution>
</executions>
</plugin>
Not sure, if this is the best approach, but it works. In case you find a more elegant implementation, let me know.
Debug Annotation (removed in version v2.1.0)
Nalu integrates a log feature that lets you trace the routes handled, controllers used, fired events, etc. The debug messages will be displayed using the browser's console.
This feature is only available during development!
To activate the log feature, you need to annotate your application class with @Debug:
@Debug()
interface MyApplication
extends IsApplication {
}This page is generated from the Nalu wiki. The wiki is the source of the text.