更新的答案
在此处提供的答案的帮助下,我更新了此答案。
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());