Hello user Hello, [[${name}]]!
``` 这是`hello.html`模板文件。 它引用随`ModelAndView`对象传递的名称变量。 ```java $ curl localhost:4567/hello/PeterHello user Hello, Peter!
``` 我们得到这个输出。 ### FreeMarker 在以下示例中,我们将把 FreeMarker 模板引擎集成到我们的 Spark 应用中。 FreeMarker 是一个完善的 Java 模板引擎。 ```java $ tree . ├── build.gradle └── src └── main ├── java │ └── com │ └── zetcode │ └── SparkFreeMarker.java └── resources └── views └── hello.ftl ``` 这是项目的目录结构。 模板文件位于`src/main/resources/views`目录中。 `build.gradle` ```java apply plugin: 'application' sourceCompatibility = '1.8' version = '1.0' mainClassName = "com.zetcode.SparkFreeMarker" repositories { mavenCentral() } dependencies { compile 'com.sparkjava:spark-core:2.5.5' compile 'org.slf4j:slf4j-simple:1.7.24' compile 'com.sparkjava:spark-template-freemarker:2.5.5' } ``` 在这里,我们有 Gradle 构建文件,其中包含`spark-template-freemarker`依赖项。 `SparkFreeMarker.java` ```java package com.zetcode; import freemarker.template.Configuration; import freemarker.template.Version; import java.io.IOException; import java.util.HashMap; import java.util.Map; import spark.ModelAndView; import spark.Request; import spark.Response; import static spark.Spark.get; import spark.template.freemarker.FreeMarkerEngine; public class SparkFreeMarker { public static void main(String[] args) throws IOException { Configuration conf = new Configuration(new Version(2, 3, 23)); conf.setClassForTemplateLoading(SparkFreeMarker.class, "/views"); get("/hello/:name", SparkFreeMarker::message, new FreeMarkerEngine(conf)); } public static ModelAndView message(Request req, Response res) { Mapparams = new HashMap<>(); params.put("name", req.params(":name")); return new ModelAndView(params, "hello.ftl"); } } ``` 我们为 FreeMarker 设置了相同的应用。 ```java Configuration conf = new Configuration(new Version(2, 3, 23)); conf.setClassForTemplateLoading(SparkFreeMarker.class, "/views"); ``` 我们用`Configuration`类配置 FreeMarker。 模板文件将放置在`views`目录中,该目录必须位于类路径上。 ```java get("/hello/:name", SparkFreeMarker::message, new FreeMarkerEngine(conf)); ``` `FreeMarkerEngine`传递给`get()`方法。 `hello.ftl` ```java Home page Hello ${name}
``` 这是`hello.ftl`模板文件; 它引用随`ModelAndView`对象传递的名称变量。 ```java $ curl localhost:4567/hello/LucyHome page Hello Lucy
``` 这是输出。 在本教程中,我们介绍了 Spark Java 框架。 您可能也对相关教程感兴趣: [Java 教程](/lang/java/),[游戏介绍](/java/play/),[Stripes 介绍](/java/stripes/)或 [Jtwig 教程](/java/jtwig/)。