前面介绍了Spring Boot的优点,然后介绍了快速创建Spring Boot项目的方法。 不清楚的人请看前面的文章。 3359 www.cn blogs.com /张伟中/类别/1657780.html。
今天主要看Thymeleaf在Spring Boot上的集成!
Thymeleaf 简介
Spring Boot 2主要支持的页面模板是Thymeleaf和Freemarker。 当然,作为Java最基本的页面模板Jsp,还支持Spring Boot,但是使用起来很麻烦。Thymeleaf作为新一代的Java模板引擎,与Velocity、FreeMarker等传统的Java模板引擎功能相似,但Thymeleaf模板的后缀为. html,应直接在浏览器中打开
这样,前端工程师就可以直接在浏览器中打开视觉样式,后端工程师也可以结合实际数据显示视觉效果。 此外,由于SpringBoot提供了Thymeleaf自动配置解决方案,因此在SpringBoot中使用Thymeleaf非常有用。
其实,Thymeleaf展示了基本的HTML,除了进行页面渲染之外,还可以渲染为一个HTML片段。 例如,我们在发送邮件时,可以将Thymeleaf作为邮件发送模板。
整合
新项目整合Thymeleaf非常简单,做项目的时候检查Thymeleaf就行了,这里就不说了。介绍如何将Thymeleaf手动集成到现有项目中。
1、pom.xml上依赖度的增加如下所示。
! 引入redis依赖关系-
从属关系
groupid org.spring框架. boot/groupid
artifactidspring -启动-启动-数据就绪/故障id
版本1.5.7 .版本/版本
将与Thymeleaf相关的配置添加到/dependency2和application.properties文件中
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# thymeleaf模板
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
spring.thyme leaf.prefix=等级路径: /模板/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thyme leaf.encoding=utf-8
spring.thyme leaf.servlet.content-type=文本/html
# #关闭缓存
spring.thyme leaf.cache=false 。
spring.thymeleaf.prefix指定模板页的路径
3、增加首页
将索引. html页添加到资源模板 thyme leaf目录中
! 文档类型html
html
赫德朗='恩'
meta字符集=' utf-8 ' /
标题/标题
/head
主体
Thymeleaf模板引擎
H1TH :文本=' $ { name } ' Hellospringboot~~~~~~/H1
/body
/htmlth:text是Thymeleaf的标签,用于处理标签主体的文本内容。
下一篇文章将介绍其他更正确的标签和使用方法。
4、控制器的创建
接下来,创建控制器。 实际上,在引入Thymeleaf依赖关系之后,不需要进行任何配置。 新的ThymeleafController包括:
软件包com.weiz .控制器;
导入Java.util .数组列表;
导入Java.util .日期;
导入Java.util .列表;
importorg.spring框架. stereotype .控制器;
importorg.spring框架. ui .模型地图;
importorg.spring框架. web.bind .注释.后期映射;
importorg.spring框架. web.bind .注释.请求映射;
import com.weiz.POJO .用户;
@Controller
@ request映射(' th ) ) )。
publicclassthymeleafcontroller {
@ request mapping (/索引) ) ) ) )。
公共字符串索引(模型映射) {
添加属性(“名称”,“类型长度索引”);
返回生命/索引;
}
(} )。
在ThymeleafController中返回逻辑视图名称。 逻辑视图名称为索引。 也就是说,必须在资源/模板thymeleaf目录下提供名为index.html的thymeleaf模板文件。
5、运行效果
在浏览器中输入http://localhost :8080/th/index以显示页面的返回结果。