SpringBoot-5-页面展示Thymeleaf
869
版权声明
我们非常重视原创文章,为尊重知识产权并避免潜在的版权问题,我们在此提供文章的摘要供您初步了解。如果您想要查阅更为详尽的内容,访问作者的公众号页面获取完整文章。
SpringBoot页面展示Thymeleaf摘要
1. 背景介绍
随着前后端分离的逐渐流行,Web开发团队能够更好地分工协作。然而,许多公司仍然需要管理传统的Web项目,因此学习如何使用SpringBoot开发Web应用仍然很重要。本文主要介绍如何使用SpringBoot2结合Thymeleaf模板引擎进行Web页面开发。
2. SpringBoot模板引擎
SpringBoot支持多种模板引擎,包括Thymeleaf、FreeMarker和Groovy,并提供了自动化配置。这些模板默认路径为src/main/resources/templates,属于静态资源。虽然JSP是Java基础的页面模板,但由于使用复杂且逐渐被淘汰,建议选择更现代的模板引擎。
3. Thymeleaf介绍及使用
3.1 Thymeleaf简介
Thymeleaf是一个XML/XHTML/HTML5模板引擎,主要用于动态页面的开发。
3.2 Thymeleaf实例
以下是使用Thymeleaf的主要步骤:
- 创建SpringBoot项目
- 编写一个控制器(
TestController) - 编写模板页面(
test.html) - 运行项目并测试页面
3.2.1 添加Thymeleaf依赖
在pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.2.2 创建控制器
使用注解@Controller创建控制器,处理路径请求并返回模板页面。例如:
@Controller
public class TestController {
@GetMapping("/test")
public String test(Model model) {
model.addAttribute("msg", "welcome my test page");
return "test";
}
}
3.2.3 编写模板页面
在src/main/resources/templates目录下创建test.html文件,其内容如下:
<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
<h1>Welcome my test page</h1>
</body>
</html>
运行项目后,在浏览器访问http://localhost:8080/test即可查看结果。
3.2.4 Thymeleaf参数配置
通过application.yml文件可以修改Thymeleaf的默认设置,例如:
spring:
thymeleaf:
cache: false
encoding: UTF-8
mode: HTML5
prefix: classpath:/templates/
suffix: .html
check-template-location: true
常见问题及解决方法:
- 页面调试时无需重启:设置
spring.thymeleaf.cache=false - 更改模板路径:修改
spring.thymeleaf.prefix - 更改模板文件扩展名:修改
spring.thymeleaf.suffix - 关闭HTML5严格校验:设置
spring.thymeleaf.mode=LEGACYHTML5
4. 总结
本文详细介绍了如何使用Thymeleaf结合SpringBoot进行动态页面开发,包括依赖配置、控制器编写、模板创建及参数设置等内容。如果文章对您有帮助,欢迎分享与支持。
springboot葵花宝典
还在用多套工具管项目?
一个平台搞定产品、项目、质量与效能,告别整合之苦,实现全流程闭环。
白皮书上线