spring boot使用thymeleaf为模板的基本步骤介绍
作者:梦想修补师 时间:2023-12-13 15:07:23
前言
在开发过程中,使用模板引擎是很有必要的。jsp已经明显跟不上时代发展了,freemarker用的够够的?换thymeleaf试试吧。
springboot官方推荐的是freemarker和thymeleaf,而thymeleaf相对于freemarker更让人感觉强大的,是他可以动态替换标签内静态内容,这样前端可以安心写页面,后台可以安心撸接口,只需要把变量替换一下即可,这种理念,不知道是VUE抄袭了thymeleaf还是thymeleaf抄袭了VUE,不过无所谓了 ,对于我们广大码奴来说,实用就好。
经过查阅资料,配置好后,现在将实现的过程分享给大家,下面话不多说了,来一起看看详细的介绍吧。
壹、pom引入
<dependency> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
贰、application.properties添加thymeleaf配置
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
<!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>
肆、测试类
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";
}
}
伍、页面效果
陆、数据渲染
VUE有个SSR(服务端渲染)的问题比较头疼,虽然也有解决方案(见我之前写的文章《 前后端分离Nuxt.js解决SEO问题 》),但总觉得还是让适合的技术做时候的业务比较好,而thymeleaf还是相当于在服务端渲染,查看页面源码如下:
来源:https://www.jianshu.com/p/b7590ec5c500
标签:spring,boot,thymeleaf模板
0
投稿
猜你喜欢
Spring Security认证机制源码层探究
2022-07-27 19:05:26
使用Feign扩展包实现微服务间文件上传
2023-04-28 01:04:31
浅谈Spring6中的反射机制
2022-06-04 13:23:33
java高并发ScheduledThreadPoolExecutor与Timer区别
2023-08-11 03:08:29
Android启动优化之延时加载的步骤详解
2023-07-10 20:43:41
Android定时器实现定时执行、重复执行、定时重复执行、定次数执行的多种方式
2022-06-30 02:07:26
如何动态替换Spring容器中的Bean
2023-05-22 20:18:59
C#生成注册码的实例代码
2022-05-16 23:35:58
Android studio 快捷键大全
2022-03-27 14:58:56
Android ListView实现上拉加载下拉刷新和滑动删除功能
2021-09-24 19:08:04
Retrofit之OKHttpCall源码分析
2021-11-13 22:08:53
Java生成二维码可添加logo和文字功能
2021-06-23 22:24:35
IDEA使用GsonFormat完成JSON和JavaBean之间的转换
2021-06-10 11:30:30
解决Android MediaRecorder录制视频过短问题
2023-04-24 01:47:56
Java中lambda表达式的基本运用
2023-09-09 08:02:36
Java如何获取Date的“昨天”与“明天”示例代码
2022-12-04 14:54:16
详解Java volatile 内存屏障底层原理语义
2023-05-08 19:25:47
java实现快速打字游戏
2022-11-05 11:16:38
C#中Linq的入门教程
2023-12-23 16:20:52
动态webservice调用接口并读取解析返回结果
2021-10-19 07:05:45