更新された回答
ここで提供される回答の助けを借りて、この回答を更新しました。
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;
}
古い回答
render()
残念ながら、独自のメソッドをオーバーライドする以外の解決策は見つかりませんでしTemplateEngine
た。以下では、ファイルの内容を読み取るために Java NIO を使用していることに注意してください。
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;
}
}
次に、ルートでHTMLTemplateEngine
次のように呼び出します。
// Render index.html on homepage
get("/", (request, response) -> new ModelAndView(new HashMap(), "index.html"),
new HTMLTemplateEngine());