Spring Boot集成FreeMarker模板引擎的详细步骤

1. 添加依赖

在Spring Boot项目中,首先需要在pom.xml文件中添加FreeMarker的依赖。如果你使用的是Spring Boot 2.x或更高版本,可以直接添加以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

如果你使用的是较老版本的Spring Boot,可能还需要单独添加FreeMarker的依赖:

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
</dependency>

2. 配置FreeMarker

Spring Boot会自动配置FreeMarker模板引擎,但你也可以通过application.propertiesapplication.yml文件来自定义配置。以下是一些常用的配置项:

application.properties配置示例:

# 模板文件路径
spring.freemarker.template-loader-path=classpath:/templates/
# 模板文件后缀
spring.freemarker.suffix=.ftl
# 是否缓存模板
spring.freemarker.cache=false
# 是否启用MVC视图解析器
spring.freemarker.enabled=true
# 设置字符编码
spring.freemarker.charset=UTF-8
# 是否允许请求访问
spring.freemarker.request-context-attribute=request

application.yml配置示例:

spring:
  freemarker:
    template-loader-path: classpath:/templates/
    suffix: .ftl
    cache: false
    enabled: true
    charset: UTF-8
    request-context-attribute: request

3. 创建模板文件

将FreeMarker模板文件放在src/main/resources/templates目录下。例如,创建一个index.ftl文件:

<!DOCTYPE html>
<html>
<head>
    <title>${title}</title>
</head>
<body>
    <h1>${message}</h1>
</body>
</html>

4. 创建Controller

在Controller中,将数据传递给模板文件。例如:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class FreeMarkerController {

    @GetMapping("/index")
    public String index(Model model) {
        model.addAttribute("title", "FreeMarker Example");
        model.addAttribute("message", "Hello, FreeMarker!");
        return "index"; // 返回模板文件的名称(不包含后缀)
    }
}

5. 启动应用并访问

启动Spring Boot应用后,访问http://localhost:8080/index,你应该会看到页面上显示:

<!DOCTYPE html>
<html>
<head>
    <title>FreeMarker Example</title>
</head>
<body>
    <h1>Hello, FreeMarker!</h1>
</body>
</html>

6. 高级用法

FreeMarker支持丰富的模板语法和功能,例如:

  • 条件语句

    <#if condition>
        条件成立时的内容
    <#else>
        条件不成立时的内容
    </#if>
    
  • 循环语句

    <#list list as item>
        ${item}
    </#list>
    
  • 宏定义

    <#macro myMacro param>
        <div>${param}</div>
    </#macro>
    <@myMacro param="Hello"/>
    
posted @   软件职业规划  阅读(47)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示