To set the base directory for serving static files in a Ratpack application we can use the baseDir
method of the ServerConfigBuilder
class. We must provide a Path
or File
to this method. If we want to serve files from the class path, for example a JAR file or directory, we can use the find
method of the class BaseDir
. The find
method will search the class path for a marker file with the name .ratpack
. If the file is found then the directory or JAR file it is found in is used as the root of the file system. Normally the root of the class path is searched, but we can change the search path with an argument for the find
method.
In the following sample Ratpack application we use the value web-resources/.ratpack.base.dir
for the BaseDir.find
method. So in our class path we must have a web-resources
directory with the file .ratpack.base.dir
that will serve as the root file system for serving static files.
// File: src/main/java/com/mrhaki/ratpack/Application.java package com.mrhaki.ratpack; import com.google.common.collect.ImmutableMap; import ratpack.groovy.Groovy; import ratpack.groovy.template.MarkupTemplateModule; import ratpack.guice.Guice; import ratpack.server.BaseDir; import ratpack.server.RatpackServer; public class Application { public static void main(String[] args) throws Exception { RatpackServer.start(server -> server .serverConfig(builder -> builder.baseDir( // Instruct Ratpack to search // class path for file // .ratpack.base.dir in the // directory web-resources. BaseDir.find("web-resources/.ratpack.base.dir")) ) .registry(Guice.registry(bindings -> bindings.module(MarkupTemplateModule.class)) ) .handlers(chain -> chain .get(context -> context.render( Groovy.groovyMarkupTemplate( ImmutableMap.of("title", "My Ratpack App"), "index.gtpl")) ) .files(files -> // The public director is resolved from // the base directory web-resources. files.dir("public") ) ) ); } }
Of course we use Gradle as build system. The Ratpack Gradle plugin automatically adds the directory src/ratpack
to the main
source set as a resources directory. Files in this directory will automatically be added to the class path. So for our example application we create the directory src/ratpack/web-resources
and create an empty file .ratpack.base.dir
in this directory. Any files and directory we now add to this directory will be accessible from the Ratpack application. Suppose we have the following contents:
$ tree -a src/ratpack src/ratpack └── web-resources ├── .ratpack.base.dir ├── public │ ├── images │ │ └── favicon.ico │ ├── lib │ ├── scripts │ └── styles └── templates └── index.gtpl 7 directories, 3 files
Written with Ratpack 1.1.1.