秒杀系统 Thymeleaf
Thymeleaf特点
学过jsp的同学应该知道jsp相当于Java和html的组合,这里我们也可以将Thymeleaf 看作jsp,参考网上一句话,这是理解thymeleaf的关键,
它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。而且浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行,当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
理解这些之后,后面的前后端分离等操作就容易理解了
如何集成Thymeleaf?
(后期会优化,先做出个大概,也符合项目迭代的思想)
1. 引入thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2. 定制化操作时需要创建配置文件
1. 新建一个Source Folder ,目录为src/main/resources,Maven标准目录结构。将创建的文件标记为源码目录。
2. 创建静态资源文件夹static,引入jquery、bootstrap等静态资源
3. 添加Thymeleaf配置项
#thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.content-type=text/html
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
#拼接前缀与后缀,去创建templates目录,里面放置模板文件
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
在resources目录下新建templates,再在里面新建hello.html页面
<!DOCTYPE html>
<!-- 使用thymeleaf,配置相应的 -->
<html xmlns:th="http://www.thymeleaf.org"> <!-- th!!! 命名空间使用 -->
<head>
<meta charset="UTF-8"/><!--<meta charset="UTF-8" /> thymeleaf模板引擎默认是Template modes:HTML5解析的,所以解析比较严格。 -->
<title>长勺</title>
</head>
<body>
<p th:text="'hello1:'+${name}"></p>
</body>
</html>
Controller里面进行测试。
补充知识点:了解@ResponseBody注解的含义
//@responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML
//数据,需要注意的呢,在使用此注解之后不会再走视图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。
@RequestMapping("/thymeleaf") //用thymeleaf返回模板,用String返回!!!
//@ResponseBody
//@responsebody表示该方法的返回结果直接写入HTTP response body中。
public String helloThymeleaf(Model model) {//0代表成功
model.addAttribute("name", "长勺");
return "hello";//他会从配置文件里面去找
}
测试结果:
总结:
集成xxx,一般是添加依赖,写入配置项,其它交给springboot,用久了会忘记一些原理性的知识,thymeleaf模板基本知道怎么用了,开发中还需要结合一些相关文档。