Ninja provides a special controller that helps to serve static assets: AssetsController. AssetsController serves static assets (like CSS, JavaScript and images) from the src/main/java/assets folder. It provides support for ETags and caching out of the box.
AssetsController will serve all assets below your src/main/java/assets folder. Therefore you have to make sure that no sensitive information is available in that folder and its subfolders.You can enable the AssetsController via the following route:
router.GET().route("/assets/{fileName: .*}").with(AssetsController.class, "serveStatic");
If a website references an image at <img src="/assets/images/logo.png" /> Ninja will serve the file at src/main/java/assets/images/logo.png. (Usually this happens inside a jar file - but for clarity we used src/main/java).
You can also serve specific files from your assets directory. A usecase is robots.txt that should be available at myserver.com/robots.txt.
To that end you can use the following route:
router.GET().route("/robots.txt").with(AssetsController.class, "serveStatic");
This route will serve your static robots.txt from src/main/java/assets/robots.txt.
The WebJars project (http://www.webjars.org/) started by James Ward is an excellent initiative that unites good old Java dependency management with static web libraries like Bootstrap.
That means that you can for instance include Bootstrap into your project via:
<dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>2.1.1</version> </dependency>
The dependency is of course transitive, and will also pull in jQuery (needed by Bootstrap). That way copying of dependencies into your assets folder is no longer needed.
In order to activate support for WebJars you need to add the following route to your project:
router.GET().route("/webjars/{fileName: .*}").with(AssetsController.class, "serveWebJars");
You can reference Bootstrap from your HTML pages via the following URL:
<link href="/webjars/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
And Bootstrap is only an example. There are a lot more WebJars available at your disposal: jQuery, Ember.js, AngularJS and much more. And everything without the need for downloading and updating stuff inside your assets directory.
Actually WebJars do nothing magic. It simply uses a Java Servlet 3.x convention that allows to reference and arbitrary static resources of a libraries' META-INF/resources folder in your application.