Updated Answer
With the help of the answer provided here, I have updated this answer.
get("/", (req, res) -> renderContent("index.html"));
...
private String renderContent(String htmlFile) {
try {
// If you are using maven then your files
// will be in a folder called resources.
// getResource() gets that folder
// and any files you specify.
URL url = getClass().getResource(htmlFile);
// Return a String which has all
// the contents of the file.
Path path = Paths.get(url.toURI());
return new String(Files.readAllBytes(path), Charset.defaultCharset());
} catch (IOException | URISyntaxException e) {
// Add your own exception handlers here.
}
return null;
}
Old Answer
Unfortunately, I have found no other solution than to override the render()
method in your own TemplateEngine
. Please note the following uses Java NIO for reading in the contents of a file:
public class HTMLTemplateEngine extends TemplateEngine {
@Override
public String render(ModelAndView modelAndView) {
try {
// If you are using maven then your files
// will be in a folder called resources.
// getResource() gets that folder
// and any files you specify.
URL url = getClass().getResource("public/" +
modelAndView.getViewName());
// Return a String which has all
// the contents of the file.
Path path = Paths.get(url.toURI());
return new String(Files.readAllBytes(path), Charset.defaultCharset());
} catch (IOException | URISyntaxException e) {
// Add your own exception handlers here.
}
return null;
}
}
Then, in your route you call the HTMLTemplateEngine
as follows:
// Render index.html on homepage
get("/", (request, response) -> new ModelAndView(new HashMap(), "index.html"),
new HTMLTemplateEngine());