使用直接HTML页面作为Spark模板的最简单方法是什么(IE,我不想通过TemplateEngine实现).
我可以使用模板引擎,如下所示:
Spark.get("/test", (req, res) -> new ModelAndView(map, "template.html"), new MustacheTemplateEngine());
Run Code Online (Sandbox Code Playgroud)
我尝试使用没有引擎的ModelAndView:
Spark.get("/", (req, res) -> new ModelAndView(new HashMap(), "index.html"));
Run Code Online (Sandbox Code Playgroud)
但是,得到的只是我的模型和视图的toString()方法:spark.ModelAndView@3bdadfd8.
我正在考虑编写自己的引擎并实现render()来执行IO来提供html文件,但是有更好的方法吗?
您不需要模板引擎.您只需要获取HTML文件的内容即可.
Spark.get("/", (req, res) -> renderContent("index.html"));
...
private String renderContent(String htmlFile) {
new String(Files.readAllBytes(Paths.get(getClass().getResource(htmlFile).toURI())), StandardCharsets.UTF_8);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
在这里提供的答案的帮助下,我已经更新了这个答案.
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;
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,我发现没有其他解决办法,只能覆盖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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在您的路线中,您拨打HTMLTemplateEngine以下内容:
// Render index.html on homepage
get("/", (request, response) -> new ModelAndView(new HashMap(), "index.html"),
new HTMLTemplateEngine());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4315 次 |
| 最近记录: |