文章目录
如果文章对您有用,请关注点赞加收藏,博主会持续更新相关的专栏笔记🫡
在 Web 开发过程中,前后端交互是一件不可避免的事情。接下来我们学习 SpringBoot 常用的页面模板框架。
SpringBoot 集成 FreeMarker
无论是语法还是配置等,FreeMarker 和 Thymeleaf 两者都有很多相似的地方。接下来,我们学习 SpringBoot 项目整合 FreeMarker 模板。
添加依赖
新建项目,在项目中加入 FreeMarker 的依赖:
<!-- 2.3.31 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>
<!-- 2.6.6 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>${springboot.version}</version>
</dependency>
添加配置
接下来配置 FreeMarker 模板属性,与 Thymeleaf 模板配置类似,唯一需要注意的是模板文件后缀配置的是 ftlh 文件。
配置文件如代码所示:
spring:
freemarker:
# 启用 freemarker 模板
enabled: true
# 是否缓存
cache: false
# Content Type
content-type: text/html
# 编码
charset: UTF-8
template-loader-path: classpath:/templates/
# 模板后缀
suffix: .ftlh
# 引用 request 的属性名称
request-context-attribute: request
# 是否暴露 request 域中的属性
expose-request-attributes: true
# 是否暴露 session 域中的属性
expose-session-attributes: true
# request 域中的属性是否可以覆盖 controller 的 model 的同名项。默认 false,如果发生同名属性覆盖的情况会抛出异常
allow-request-override: true
# session 域中的属性是否可以覆盖 controller 的 model 的同名项。默认 false,如果发生同名属性覆盖的情况会抛出异常
allow-session-override: true
# 暴露官方提供的宏
expose-spring-macro-helpers: true
# 启动时检查模板位置是否有效
check-template-location: true
# 优先加载文件系统的模板
prefer-file-system-access: true
settings:
datetime_format: yyyy-MM-dd HH:mm:ss # date 输出格式化
template_update_delay: 30m # 模板引擎刷新时间
default_encoding: UTF-8 # 默认编码
创建 Controller 测试
接下来,创建一个 FreeMarkerController 进行测试:
package com.you.controller;
import com.you.service.PlanTextStrategy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import javax.annotation.Resource;
import java.util.*;
/**
* @author 爱淋雨的鼬先生
* @date 2024/11/02
*/
@Controller
public class FreeMarkerController {
@Resource
private PlanTextStrategy planTextStrategy;
/**
* Freemarker 基础模型数据测试
*
* @param model 数据模型
* @return 跳转到 basic 页面
*/
@GetMapping("freemarkerBaseData")
public String basic(Model model) {
// 数据准备
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>(16);
map1.put("name", "苹果");
map1.put("price", 4.5);
Map<String, Object> map2 = new HashMap<>(16);
map2.put("name", "香蕉");
map2.put("price", 6.3);
list

最低0.47元/天 解锁文章
1006

被折叠的 条评论
为什么被折叠?



