freemarker搭建
时间: 2025-01-12 14:40:05 浏览: 22
如何搭建Freemarker环境
创建 Maven 工程
为了方便管理依赖项,建议使用 Maven 或 Gradle 构建工具。这里以 Maven 为例:
<dependencies>
<!-- 添加 FreeMarker 依赖 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<!-- 如果要与 Spring Boot 结合使用,则还需要添加以下依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
初始化配置
创建 src/main/resources
目录下的 templates
文件夹用于存放模板文件。
编写简单的 Java 类来加载并渲染模板[^1]:
import freemarker.template.Configuration;
import freemarker.template.Template;
public class FreemarkerDemo {
private static final String TEMPLATE_PATH = "classpath:/templates/";
public Configuration getConfiguration() throws IOException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
cfg.setClassForTemplateLoading(FreemarkerDemo.class, "/templates");
cfg.setDefaultEncoding("UTF-8");
return cfg;
}
public void renderTemplate(Map<String, Object> dataModel) throws Exception {
Template template = configuration.getTemplate("example.ftl");
Writer out = new OutputStreamWriter(System.out);
template.process(dataModel, out);
}
}
编写第一个模板文件
在 resources/templates/
下新建名为 example.ftl
的文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello ${name}</title>
</head>
<body>
<h1>Welcome to Freemarker Demo!</h1>
<p>This is a simple example of using Freemarker.</p>
</body>
</html>
通过上述步骤可以成功建立一个基本的FreeMaker开发环境,并能够运行简单的模板测试案例[^4]。
相关推荐


















