Thymeleaf

本文深入探讨了Thymeleaf模板引擎的功能与用法,包括其在Web开发中的优势,如处理HTML、XML、JavaScript和CSS的能力,以及如何在Spring Boot项目中配置和使用Thymeleaf。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Thymeleaf

●Thymeleaf是面向Web和独立环境的现代服务器端Java模板引擎能够处理HTML,XML,JavaScript,CSS甚至纯文本。
●Thymeleaf旨在提供一个优雅的、高度可维护的创建模板的方式。 为了实现这一标,Thymeleaf建立在自然模板的概念上,将其逻辑入到模板文件中,不会影响模板设计原型。这改善了设计的沟通,弥合了设计和开发团队之间的差距。
●Thymeleaf从设计之初就遵循Web标准——特别是HTML5标准 ,如果需要,Thymeleaf允许您创建完全符合HTML5验证标准的模板。

网址:https://docs.spring.io/spring-boot/docs/2.0.7.RELEASE/reference/htmlsingle

引依赖:

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>1.5.10.RELEASE</version>
</parent>

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-thymeleaf</artifactId>
	</dependency>

	<dependency><!--开发者工具集(自动重启).-->
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-devtools</artifactId>
		<optional>true</optional>
	</dependency>
	
	<dependency><!-- 小辣椒 -->
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
		<version>1.16.2</version>
		<scope>provided</scope>
	</dependency>
</dependencies>

application.yml:

spring: 
  thymeleaf:
#缓存.开发的时候改成false,真正上线的时候改成true,这样修改之后马上生效,便于调试.
  	cache: false
#html 存放目录
  	prefix: classpath:/static/
#端口
server: 
	port: 5050

html:

html 对 thymeleaf 来说都叫模板.

静态资源(html,图片)可以放在:/META-INF/maven/META-INF/resources(表示在src/main /resources目录下建一个resources,这种方式不建议),/resources/static/public,或 /templates任意一个目录下

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	holler ${sex}  <!--普通的HTML会直接输出,但是现在是 thymeleaf 里面模板,所以会把${sex}解析成作用域()里面的值-->
	
</body>
</html>

Main:

@SpringBootApplication
public class ThymeleafMain {
	
	public static void main(String[] args) {
		SpringApplication.run(ThymeleafMain.class, args);
	}
}

输出结果:
在这里插入图片描述
结果没有解析,thymeleaf在直接访问的结果下还是html,要从控制层经过 才会当成 thymeleaf 模板(将来我们的程序(需要控制的)一定是从控制层经过的,而不是直接访问 html 因为我们经过了一个跳转的通道,别人就不知道你视图层是怎么过来的(在后台操作的))。
控制层:

@Controller
public class ThyController {
	@GetMapping("index")
	public String index(Model model,HttpServletRequest request) {
		return "idx"; //返回html文件名.
		//有默认值 spring.thymeleaf.suffix=.html 会自动加.html,所以不需要写
	}
}

结果 loca:5050/index
在这里插入图片描述
因为 thymeleaf 的 html 语句要求是极度规范的,规范到每一个标签都要有结尾(强制的检测)

解决:
配置:spring.thymeleaf.mode = LEGACYHTML5
需要依赖:

<dependency>
	<groupId>nekohtml</groupId>
	<artifactId>nekohtml</artifactId>
	<version>1.9.6.2</version>
</dependency>
  1. 配置是回避 html 进行严格的检查的配置,当然你需要提前引入 nekohtml 依赖.
  2. 使用 springboot 的 thymeleaf 模板是默认会对html进行严格的检查,导致当你的标签没有闭合时就会通不过.nekohtml依赖就可以解决这个问题.
  3. $不是放到哪都可以解析的.
    详情请参考:https://blog.youkuaiyun.com/zrk1000/article/details/72667478

创建html:

<!DOCTYPE html>
<!-- 自定义标签 -->
<html xmlns:th="http://www.thymeleaf.org">
<!--或者:xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"-->
<head>
  1. 里面的属性都已 th:开头,也只能检查到 th:开头的。
  2. 带有th:开头的属性都是有特定语法的 ,里面是一个表达式,不一定就是一个字符串,不打单引号就是一个字符串,加了单引号可以做 java 里面的操作,还可以调 java 里面的方法.
  3. 只要是 th: 里面的都可以使用表达式.

在这里插入图片描述

标签:

<!-- th:text 替换标签内部的内容,会把<转译 ,里面是没有 html 标签的-->
	<div th:text="'<font color=red>欢迎</font>'">
		光临  
	</div>
	<!-- th:utext 不转译,直接打印 -->
	<div th:utext="'<font color=red>欢迎</font>'">
		光临   
	</div> -->
	<div th:utext="*{user.name}"> <!-- *{user.name} 跟  ${user.name} 一样-->
		光临
	</div><br/>
	<!--2.多以上的thymeleaf 支持[[${sex}]] 方式-->

*{} :选择变量表达式:

<div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
    <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p> 
    <p>Nationality: <span th:text={nationality}">Saturn</span>.</p>
</div> 
<!--等价于-->
<div>
    <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p> 
    <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p> 
    <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>
<!--当然了,这两者可以混合使用
还有一种方式-->
<div>
    <p>Name: <span th:text="*{session.user.name}">Sebastian</span>.</p> 
    <p>Surname: <span th:text="*{session.user.surname}">Pepper</span>.</p> 
    <p>Nationality: <span th:text="*{session.user.nationality}">Saturn</span>.</p>
</div> 

对于 html5 元素名称的另一种友好写法

<div th:object="${user}"> <!-- 一旦用了th:object标签里面就没有user名字了,就不能点了. -->
		<p th:text="*{name}"></p> <!-- 高版本支持*{object.name} -->
		<p th:text="*{id}"></p> <!-- 只能在代码块内部才可以直接取属性 -->
		<!-- 没有object,* 号 与  $ 效果一样;否则,*只能用于*{id},*{name} -->
		
		<p th:text="${user1.userName}"></p>
		<!-- 高版本里面支持:<p th:text="*{user1.userName}"></p> -->
		
		<!-- 使用HttpServletRequest 要用session点	jsp里面叫sessioncope -->
		<p th:text="${session.user2.userId}"></p>
	</div><br/>

	<!-- 直接调方法 ,把方法的返回值打印出来-->
	<p th:text="${session.user2.toString()}"></p>

循环:
html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="per" method=get>
		查询:<input id="myKeyWord" type="text" name="keyword"/>
		<input type="submit" value="搜索"/>
	</form>
	<table>
		<tr style='width:100%'>
			<th>国家</th>
			<th>姓名</th>
			<th>描述</th>
		</tr>
		<tr style='width:100%' th:each="person ,iterStat : ${personList}"
		
			th:style="${iterStat.odd}?'background-color:#B4ECF0':''"
		>
			<td th:text="${person.country}"></td>
			<td th:text="${person.name}"></td>
			<td th:text="${person.desc}"></td>
		</tr>
	</table>
</body>
</html>

控制层:

@Controller
public class ThyController {
	
	@GetMapping("index")
	public String index(Model model,HttpServletRequest request) {
		//model.addAttribute("sex","mg");
		
		Map map = new HashMap();
		map.put("id",5);
		map.put("name","mg");
		model.addAttribute("user",map);
		
		User user = new User("2","lt");
		model.addAttribute("user1",user);
		
		User user1 = new User("9","lt");
		request.getSession().setAttribute("user2",user1);
		
		return "idx";
	}
	//循环.
	@Autowired
	private PersonDao persondao;
	
	@GetMapping("/per")
	public String person(String keyword,Model model) {
		List<Person> personList = persondao.findByDesc(keyword);
		model.addAttribute("personList",personList);
		
		return "person";
	}

	
	@GetMapping("/inc")
	public String inc() {
		return "newOne";
	}
}
<!DOCTYPE html>
<html xmlns:th="http://www/thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div>
		新闻  视频  图片  军事  体育  娱乐  财经  科技  时尚  游戏  星座
		<script>alert("sleep")</script>
		<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
	</div>

</body>
</html>
------------------------------
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div th:include="header :: myheader">
	</div>
	
	<script>
		alert($);
	</script>
	中新网12月6日电 据俄罗斯卫星网援引塞尔维亚当地网站报道,塞尔维亚中部一只名为Belka的山羊吃掉了主人2万欧元现金,随后被做成了烤肉。

报道称,位于贝尔格莱德以南80公里处的一个家庭,准备了2万欧元现金用于购买10公顷的土地。他们数了钱,并且在等卖家时候,将钱放在了房子的桌上。

</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值