springboot模板引擎使用之freemarker
1、引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
2、修改配置文件application.properties
# freemarker静态资源配置 spring.resources.static-locations=classpath:/static/ spring.mvc.static-path-pattern=/static/** # 设定ftl文件路径 spring.freemarker.tempalte-loader-path=classpath:/templates # 关闭缓存,及时刷新,上线生产环境需要修改为true spring.freemarker.cache=false #设定Template的编码 spring.freemarker.charset=UTF-8 #是否检查templates路径是否存在 spring.freemarker.check-template-location=true #设定Content-Type spring.freemarker.content-type=text/html #设定所有request的属性在merge到模板的时候,是否要都添加到model中 spring.freemarker.expose-request-attributes=true #设定所有HttpSession的属性在merge到模板的时候,是否要都添加到model中. spring.freemarker.expose-session-attributes=true #指定RequestContext属性的名. spring.freemarker.request-context-attribute=request #设定模板的后缀 spring.freemarker.suffix=.ftl #设定freemarker模板的前缀 #spring.freemarker.prefix
3、创建一个UserController.java
package com.xdw.springbootdemo5; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class UserController { /** * 采用model往request域中存值,存入2个普通的字符串 * @param model * @return */ @RequestMapping(value = "/userinfo1",method = RequestMethod.GET) public String userinfo1(Model model) { String username = "xiadewang"; String password = "123456"; model.addAttribute("username", username); model.addAttribute("password", password); return "userinfo1"; } }
4、创建一个ftl后缀的模板页面userinfo1.ftl
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <p>用户名:${username}</p> <p>密码:${password}</p> </head> <body> </body> </html>
5.运行项目访问
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?