您的位置:首页 > 编程语言 > Java开发

SpringBoot秒杀系统实战03-集成Thymeleaf做页面模板

2020-07-14 06:02 513 查看
文章目录

Thymeleaf是什么?

简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。

特点:

1.Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
   2.Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
   3. Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

集成Thymeleaf

1.引入依赖

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

2.生成配置文件

  • 新建一个一个Source Folder ,目录为src/main/resources。
  • 创建静态资源文件夹static,引入jquery、bootstrap等静态资源

SpringBoot会默认找一个叫application.properties的文件。

添加Thymeleaf配置项

[code]#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页面

[code]<!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>AA</title>
</head>
<body>
<p th:text="'hello1:'+${name}"></p>
</body>
</html>

Controller里面进行测试。

[code]//@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", "pitt");
return "hello";//他会从配置文件里面去找
}

注意:取消@ResponseBody注解!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐