SpringBoot入门之Thymeleaf的使用
在.net的MVC3 或更高版本等支持 Razor 的框架里使用cshtml,Razor是一种简单的编程语法,用于在网页中嵌入服务器端代码.在使用springboot开发mvc时也有与.net类似的视图引擎.
Spring Boot提供了大量的模板引擎,包含了FreeMarker,Groovy,Thymeleaf,Velocity和Mustache,Spring Boot中推荐使用Thymeleaf作为模板引擎,因为Thymeleaf提供了完美的Spring MVC的支持。Thymeleaf是一个java类库,它是一个xml/xhtml/html5的模板引擎,可以作为MVC的Web应用的View层。Thymeleaf还提供了额外的模块与Spring MVC集成,所以我们可以使用Thymeleaf完全替代JSP。
一、Thymeleaf配置
Thymeleaf有哪些属性可以配置呢,我们可以在org.springframework.boot.autoconfigure.thymeleaf下的ThymeleafProperties.class找到属性,springboot约定大于配置,所以在ThymeleafProperties.class中也都有默认值,如果我们想改变默认值可以在application.properties设置。这里用的都是它的默认值。默认路径在templates下,文件是html文件。
二、项目引入Thymeleaf
这里还是在上一springboot博客的例子基础上进行修改,这里需要在pom.xml引入Thymeleaf,这里要注意一下,由于用的是spring5,如果引入的Thymeleaf版本不正确就可能会报错,而且不同的spring引入Thymeleaf的artifactId也不一样。
<dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.9.RELEASE</version> </dependency>
同时如果在html页面使用还需要在html增加一行
<html xmlns:th="http://www.thymeleaf.org">
三、测试
这里创建了一个Controller和一个html.Thymeleaf的属性都是用的默认的属性值,如果需要改变可以在resources/application.properties下更改,前缀名是spring.thymeleaf。
package com.example.demo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; //@RestController @Controller public class HelloController { @RequestMapping(value = "/hello",method = RequestMethod.GET) public String hello(Model model) { model.addAttribute("name", "Cuiyw"); return "hello"; } }
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>hello</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p th:text="'Hello!, ' + ${name} + '!'" ></p> </body> </html>
作者:社会主义接班人
出处:http://www.cnblogs.com/5ishare/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果文中有什么错误,欢迎指出。以免更多的人被误导。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?