携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第6天,点击查看活动详情
工作两年了,自我感觉前后端分离已经是大势所趋更确切的说是已经占领的市场,但是视图层技术还占有一席之地。Spring Boot对视图层技术提供很多默认的配置,还有其他视图技术也都对springboot进行了开发,官方推荐使用的模板引擎是Thymeleaf,不过像FreeMarker也支持,JSP技术在这里并不推荐使用。
一、整合Thymeleaf
Thymeleaf支持HTML原型,让前端工程师在可以直接进行开发调试,也可以让后端工程师结合真实数据查看效果。简直不要太放拜年奥
1、创建工程、添加依赖
新建一个Spring Boot工程,然后添加spring-boot-starter-web和spring-boot-starter-thymeleaf依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
配置
- 引入之后我们就需要进行简单的配置或者直接使用springboot的默认配置也行
#是否开启缓存,开发时可以设置为false,默认为true
spring.thymeleaf.cache=true #检查模板是否存在,默认为true
spring.thymeleaf.check-template=true #检查模板位置是否存在,默认为true
spring.thymeleaf.check-template-location=true #模板文件编码
spring.thymeleaf.prefix=classpath:/templates/ #Content-Type配置
spring.thymeleaf.servlet.content-type=text/html #模板文件后缀
spring.thymeleaf.suffix=.html
创建视图
在resources目录下的templates目录中创建index.html , 只需要这样我们再把前端的代码copy过来即可。这样后端程序就可以渲染页面了。简直方便。
特点
- 动静结合:在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
- 与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像以前操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别。