在完成配置之后,举一个简单的例子,在快速入门工程的基础上,举一个简单的示例来通过Thymeleaf渲染一个页面。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
@Controller public class HelloController { @RequestMapping ( "/" ) public String index(ModelMap map) { // 加入一个属性,用来在模板中读取 map.addAttribute( "host" , "http://blog.didispace.com" ); // return模板文件的名称,对应src/main/resources/templates/index.html return "index" ; } } <!DOCTYPE html> <html> <head lang= "en" > <meta charset= "UTF-8" /> <title></title> </head> <body> <h1 th:text= "${host}" >Hello World</h1> </body> </html> |
如上页面,直接打开html页面展现Hello World,但是启动程序后,访问http://localhost:8080/
,则是展示Controller中host的值:http://blog.didispace.com
,做到了不破坏HTML自身内容的数据逻辑分离。
更多Thymeleaf的页面语法,还请访问Thymeleaf的官方文档查询使用。
Thymeleaf的默认参数配置
如有需要修改默认配置的时候,只需复制下面要修改的属性到application.properties
中,并修改成需要的值,如修改模板文件的扩展名,修改默认的模板路径等。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
# Enable template caching. spring.thymeleaf.cache= true # Check that the templates location exists. spring.thymeleaf.check-template-location= true # Content-Type value. spring.thymeleaf.content-type=text/html # Enable MVC Thymeleaf view resolution. spring.thymeleaf.enabled= true # Template encoding. spring.thymeleaf.encoding=UTF- 8 # Comma-separated list of view names that should be excluded from resolution. spring.thymeleaf.excluded-view-names= # Template mode to be applied to templates. See also StandardTemplateModeHandlers. spring.thymeleaf.mode=HTML5 # Prefix that gets prepended to view names when building a URL. spring.thymeleaf.prefix=classpath:/templates/ # Suffix that gets appended to view names when building a URL. spring.thymeleaf.suffix=.html spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved. |
支持JSP的配置
Spring Boot并不建议使用,但如果一定要使用,可以参考此工程作为脚手架:JSP支持
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具