服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - spring boot使用thymeleaf为模板的基本步骤介绍

spring boot使用thymeleaf为模板的基本步骤介绍

2021-03-19 12:10梦想修补师 Java教程

Spring Boot项目的默认模板引擎是Thymeleaf,这没什么好说的,个人觉得也非常好,下面这篇文章主要给大家介绍了关于spring boot使用thymeleaf为模板的相关资料,需要的朋友可以参考借鉴,下面来一起学习学习吧。

前言

在开发过程中,使用模板引擎是很有必要的。jsp已经明显跟不上时代发展了,freemarker用的够够的?换thymeleaf试试吧。

springboot官方推荐的是freemarker和thymeleaf,而thymeleaf相对于freemarker更让人感觉强大的,是他可以动态替换标签内静态内容,这样前端可以安心写页面,后台可以安心撸接口,只需要把变量替换一下即可,这种理念,不知道是vue抄袭了thymeleaf还是thymeleaf抄袭了vue,不过无所谓了 ,对于我们广大码奴来说,实用就好。

经过查阅资料,配置好后,现在将实现的过程分享给大家,下面话不多说了,来一起看看详细的介绍吧。

壹、pom引入

?
1
2
3
<dependency>  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-thymeleaf</artifactid>
 </dependency>

贰、application.properties添加thymeleaf配置

?
1
2
3
4
5
6
7
8
9
spring.thymeleaf.cache=false
spring.thymeleaf.check-template=true
spring.thymeleaf.check-template-location=true
spring.thymeleaf.content-type=text/html
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=utf-8
spring.thymeleaf.mode=html5
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

叁、编写html

?
1
2
3
4
5
6
7
8
9
10
11
<!doctype html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
  xmlns:th="http://www.thymeleaf.org">
<head>
 <title>demo</title>
</head>
<body>
<p>这是第一段</p>
<p th:text="${textvalue}">这是第二段</p>
</body>
</html>

肆、测试类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.mos.easyboot.admin.controller;
import org.springframework.stereotype.controller;
import org.springframework.ui.model;
import org.springframework.web.bind.annotation.requestmapping;
@controller
@requestmapping("demo")
public class democontroller {
 @requestmapping("index")
 public string index(model model){
 string textvalue = "上士闻道,仅能行之;中士闻道,若存若亡;下士闻道,大笑之。" +
  "不笑不足以为道。" +
  "故建言有之:明道若昧;进道若退;夷道若颣(lei);上德若谷,大白若辱,广德若不足,建德若偷,质真若渝;大方无隅;大器免成;大音希声;大象无形。" +
  "道隐无名。" +
  "夫唯道,善始且善成。";
 model.addattribute("textvalue",textvalue);
 return "demo/demo";
 }
}

伍、页面效果

spring boot使用thymeleaf为模板的基本步骤介绍

陆、数据渲染

vue有个ssr(服务端渲染)的问题比较头疼,虽然也有解决方案(见我之前写的文章《 前后端分离nuxt.js解决seo问题 》),但总觉得还是让适合的技术做时候的业务比较好,而thymeleaf还是相当于在服务端渲染,查看页面源码如下:

spring boot使用thymeleaf为模板的基本步骤介绍

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:https://www.jianshu.com/p/b7590ec5c500

延伸 · 阅读

精彩推荐