1

TemplateEngineストレートな HTML ページを Spark テンプレートとして使用する最も簡単な方法は何ですか (IE、実装はしたくありません)。

次のように、テンプレート エンジンをうまく使用できます。

Spark.get("/test", (req, res) -> new ModelAndView(map, "template.html"), new MustacheTemplateEngine());

そして、エンジンなしで ModelAndView を使用してみました:

Spark.get("/", (req, res) -> new ModelAndView(new HashMap(), "index.html"));

しかし、それはモデルとビューの toString() だけですspark.ModelAndView@3bdadfd8

独自のエンジンを作成し、render() を実装して IO を実行して html ファイルを提供することを考えていますが、より良い方法はありますか?

4

3 に答える 3

7

テンプレート エンジンは必要ありません。必要なのは、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);
}
于 2015-12-01T15:09:35.950 に答える
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;
}

古い回答

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());
于 2015-11-19T15:14:02.157 に答える
2

役立つ別の One Line ソリューション:

get("/", (q, a) -> IOUtils.toString(Spark.class.getResourceAsStream("/path/to/index.html")));

このインポートが必要です: import spark.utils.IOUtils;

ソース: https://github.com/perwendel/spark/issues/550

于 2016-10-27T14:57:28.927 に答える