springboot 整合Thymeleaf
Thymeleaf是新一代Java模板引擎,类似于Velocity、FreeMarker等传统Java模板引擎。与传统Java模板引擎不同的是,Thymeleaf支持HTML原型,既可以让前端工程师在浏览器中直接打开查看样式,也可以让后端工程师结合真实数据查看显示效果。同时,Spring Boot提供了Thymeleaf自动化配置解决方案
添加依赖
添加spring-boot-starter-web和spring-boot-starter-thymeleaf依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
配置Thymeleaf
Spring Boot为Thymeleaf提供了自动化配置类ThymeleafAutoConfiguration,相关的配置属性在ThymeleafProperties类中
如果开发者想对默认的Thymeleaf配置参数进行自定义配置,那么可以直接在application.properties中进行配置,部分常见配置如下:
spring:
thymeleaf:
cache: false # thymeleaf缓存是否开启 开发时建议关闭 否则更改页面后不会实时展示效果
encoding: UTF-8 # thymeleaf编码格式
# mode: LEGACYHTML5 # thymeleaf对html校验很严格,用这个去除thymeleaf严格校验
prefix: classpath:/templates/ # thymeleaf模板文件前缀
suffix: .html # thymeleaf模板文件后缀
配置控制器
1 2 3 4 5 6 7 8 9 | @GetMapping ( "/templates/index" ) public ModelAndView index() { Locale locale = LocaleContextHolder.getLocale(); ModelAndView mv = new ModelAndView(); mv.addObject( "message" , messageSource.getMessage( "message" , null , locale)); mv.setViewName( "index" ); return mv; } |
创建视图
在resources目录下的templates目录中创建index.html,具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 | <! DOCTYPE html> < html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> < head > < meta charset="UTF-8"> < title >Title</ title > </ head > < body > < a href="/templates/index?lang=en_US">English(US)</ a > < a href="/templates/index?lang=zh_CN">简体中文</ a > < p >< label th:text="#{message}"></ label ></ p > </ body > </ html > |
关于Thymeleaf的更多资料,可以查看https://www.thymeleaf.org。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!