## 前言
模版引擎千千万,今个说说Thymeleaf,主要是不想在混用jsp标签和使用jsp后缀文件,
直接使用html文件,便于前后端分离。
如果觉得布局不够美观,可以看我的个人博客:http://nealma.com
开发环境:
OS: Mac 10.11.6
IDE: IDEA
Build: Maven
### 依赖
Spring Boot天生内置了对Thymeleaf的支持,简化了配置,加速开发。只需要引入如下
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
### 配置
在application.properties文件里加入如下
```
#thymeleaf
#我倾向于放在webapp/WEB-INF的目录下,spring.thymeleaf.prefix=/templates
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
```
在src/main/resources/templates/文件夹下,存放你的模版文件,其实在应用启动的时候,
TemplateEngine,ThymeleafViewResolver会自用实例化。
### 空间指定
没有指定空间,总是飘红,还是加上吧
```
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
```
### 最简用例
* Controller
```
/**
*
* 商品信息
*/
@RestController
public class GoodsPageController extends BaseController {
/**
* 商品列表
*/
@RequestMapping(value={"/goods/list"}, method=RequestMethod.GET)
@PermitAll
public ModelAndView list(Model model) {
LOGGER.info("|--> {}", this.getRequest().getRequestURI());
model.addAttribute("name", "neal");
Map<String, Object> map=new HashMap<>();
map.put("id", 1);
map.put("title", "小怪兽来了");
Map<String, Object> map1=new HashMap<>();
map1.put("id", 2);
map1.put("title", "小怪兽来了");
model.addAttribute("list", Arrays.asList(new Object[]{map,map1}));
return new ModelAndView("/index");
}
}
```
* 创建src/main/resources/templates/index.html
```
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Thymeleaf Mini Demo</title>
</head>
<body>
Hello, <b th:text="${name}">Name</b>
<div th:each="item:${list}">
<b th:text="${item.id}">ID</b>
<b th:text="${item.title}">Title</b>
</div>
</body>
</html>
```
### 结束
使用过程中,发现thymeleaf对于html的语法要求的很严格,每个标签都要有结束tag。我的一个页面
<link > <img> 没有"/",导致报错;还有就是属性必须是"=",即key=value, 在input中我使用了disable,结果报错了
于是改成disable="disable".
前面我们讲解了Spring Boot项目的创建、Spring Boot结构信息,自动配置功能等,那么Springboot创建出来,我们最终是要做web开发的,所以我们这章讲解如何用SpringBoot做web开发。
Spring boot提供了一套完整的web开发流程,从前端到后台,再到数据库,定时任务,消息队列等都可以支持.一般利用Spring框架开发一个Web应用有两种方式:
Spring Boot 提供了spring-boot-starter-web来为Web开发予以支持,spring-boot-starter-web为我们提供了嵌入的Tomcat以及SpringMVC的依赖,用起来很方便。另外,我们还要用到模板引擎,用来显示视图页面,springboot支持的模板引擎很多,包括Thymeleaf, FreeMarker, Groovy, Mustache, Velocity, JSP等,
之前Java第七模块讲解Thymeleaf时已经讲解过jsp现在不建议使用,我们这里用Thymeleaf来做模板。
这种方式前端开发和后端开发完全分离,可以由前后端两个团队分开同步开发,只需要协商好接口就行,前端负责开发页面并调用后端接口展示数据,后端负责提供Restful风格的接口.
Thymeleaf相关知识看Java第七模块。
这里直接讲解Springboot中怎么整合Themeleaf模板。
我们先在springboot中使用Thymeleaf,看看简化了哪些步骤,再来分析为什么会简化。
选择web依赖
选择Thymeleaf依赖
html标签中添加 xmlns:th="http://www.thymeleaf.org"
通过上面的操作,我们会发现我们不需要配置视图的前缀和后缀了,这是因为系统已经帮我自动配置了。
自动配置信息在:
可以看到 默认配置的前缀为templates文件夹
后缀为.html
所以我们只需要把html页面建在templates文件夹下就可以。
比如将后缀名改为.htm
先找到后缀名配置名称:
然后在配置文件application.properties中添加
spring.thymeleaf.suffix=.htm
添加后缀名为.htm的模板文件
运行:
对html+js的传统设计,现在很多网站都采用div&css+标签化+模块化的设计。模板引擎根据一定的语义,将数据填充到模板中,产生最终的HTML页面。模板引擎主要分两种:客户端引擎和服务端引擎。
客户端渲染:
模板和数据分别传送到客户端,在客户端由JavaScript模板引擎渲染出最终的HTML视图。将模板渲染放置在客户端做,可以降低服务端的压力,并且如果前端内容分别来自多个后台系统,而这些后台的架构各不相同(Java、.NET、Ruby等),则服务器端渲染需要采用不同的技术,模板资源无法共享。
服务端渲染:
引擎在服务器端将模板和数据合成,返回最终的html页面,相对于客户端渲染,数据存储更加安全。主要有freemarker、velocity、thymeleaf等。
相较与其他的模板引擎,thymeleaf它有如下三个特点:
(a) 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,同时也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
(b) 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
(c) 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
1、新建项目sc-thymeleaf,对应的pom.xml文件如下
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>spring-cloud</groupId> <artifactId>sc-thymeleaf</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>sc-thymeleaf</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> </parent> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <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> </dependencies> </project>
2、新建springboot启动类
package sc.thymeleaf; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ThymeleafApplication { public static void main(String[] args) { SpringApplication.run(ThymeleafApplication.class, args); } }
3、新建配置文件application.yml
server: port: 8090 spring: application: name: sc-thymeleaf thymeleaf: cache: false
说明:thymeleaf所有的配置项可以参考类
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties
常用配置说明:
# THYMELEAF (ThymeleafAutoConfiguration)
#开启模板缓存(默认值:true)
spring.thymeleaf.cache=true
#Check that the template exists before rendering it.
spring.thymeleaf.check-template=true
#检查模板位置是否正确(默认值:true)
spring.thymeleaf.check-template-location=true
#Content-Type的值(默认值:text/html)
spring.thymeleaf.content-type=text/html
#开启MVC Thymeleaf视图解析(默认值:true)
spring.thymeleaf.enabled=true
#模板编码
spring.thymeleaf.encoding=UTF-8
#要被排除在解析之外的视图名称列表,用逗号分隔
spring.thymeleaf.excluded-view-names=
#要运用于模板之上的模板模式。另见StandardTemplate-ModeHandlers(默认值:HTML5)
spring.thymeleaf.mode=HTML5
#在构建URL时添加到视图名称前的前缀(默认值:classpath:/templates/)
spring.thymeleaf.prefix=classpath:/templates/
#在构建URL时添加到视图名称后的后缀(默认值:.html)
spring.thymeleaf.suffix=.html
#Thymeleaf模板解析器在解析器链中的顺序。默认情况下,它排第一位。顺序从1开始,只有在定义了额外的TemplateResolver Bean时才需要设置这个属性。
spring.thymeleaf.template-resolver-order=
#可解析的视图名称列表,用逗号分隔
spring.thymeleaf.view-names=
其实完全可以使用不用配置,但是Spring Boot官方文档建议在开发时将缓存关闭,默认为true
4、新建Controller
package sc.thymeleaf.controller; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import sc.thymeleaf.model.User; @Controller public class UserController { @RequestMapping("/user/list") public String userList2(Model model) throws Exception { model.addAttribute("hello", "Hello, thymeleaf!"); List<User> list=new ArrayList<User>(); User u1=new User(); u1.setId(1); u1.setName("huangjinjin"); u1.setAge(30); u1.setPosition("cto"); list.add(u1); User u2=new User(); u2.setId(2); u2.setName("huang ge"); u2.setAge(32); u2.setPosition("cco"); list.add(u2); model.addAttribute("list", list); return "/user/list"; } }
5、新建模板文件
说明:Thymeleaf默认模板路径在classpath:/templates/下
6、运行ThymeleafApplication.java类,启动项目
7、在浏览器输入http://127.0.0.1:8090/user/list
这里不深入讲解Thymeleaf模板引擎的语法,如果想学习Thymeleaf的基本语法可以参考https://www.cnblogs.com/ityouknow/p/5833560.html或者自行找些资料学习
*请认真填写需求信息,我们会在24小时内与您取得联系。