四时宝库

程序员的知识宝库

实战SpringBoot系列 - 集成Thymeleaf构建Web应用

1、简介

Thymeleaf是用来开发Web和独立环境项目的服务器端的Java模版引擎;Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP。

Spring官方支持的服务的渲染模板中,并不包含jsp。而是Thymeleaf和Freemarker等,而Thymeleaf与SpringMVC的视图技术,及SpringBoot的自动化配置集成非常完美,几乎没有任何成本,你只用关注Thymeleaf的语法即可。

2、Thymeleaf的特点

动静结合:

Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

开箱即用:

它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

多方言支持:

Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速地实现表单绑定、属性编辑器、国际化等功能。

与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像以前操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别。

3、整合Spring Boot

3.1、引入依赖

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

</dependency>

</dependencies>

3.2、资源目录

Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:

/static

/public

/resources

/META-INF/resources

举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件pic.jpg。 启动程序后,尝试访问http://localhost:8080/pic.jpg。如能显示图片,配置成功。

SpringBoot的默认模板路径为:src/main/resources/templates

3.3、新建页面

这里我在src/main/resources/templates下面添加一个index.html首页,同时引用到一些css、js文件,看看Thymeleaf 3的语法:


<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="renderer" content="webkit">
<title>首页</title>
<link rel="shortcut icon" th:href="@{/favicon.ico}"/>
<link th:href="@{/static/css/bootstrap.min.css}" rel="stylesheet"/>
<link th:href="@{/static/css/font-awesome.min.css}" rel="stylesheet"/>
</head>
<body class="fixed-sidebar full-height-layout gray-bg" style="overflow:hidden">
<div id="wrapper">
<h1 th:text="${msg}"></h1>
</div>
<script th:src="@{/static/js/jquery.min.js}"></script>
<script th:src="@{/static/js/bootstrap.min.js}"></script>
</body>
</html>

页面中几个地方说明一下:

1
2

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

加上这个命名空间后就能在页面中使用Thymeleaf自己的标签了,以th:开头。

连接语法 th:href="@{/static/css/bootstrap.min.css}"

访问Model中的数据语法 th:text="${msg}"

这里我在页面里显示的是一个键为msg的消息,需要后台传递过来。

3.4、编写Controller


public class IndexController {
private static final Logger _logger = LoggerFactory.getLogger(IndexController.class);
/**
* 主页
*
* @param model
* @return
*/
@RequestMapping({"/", "/index"})
public String index(Model model) {
model.addAttribute(
"msg", "welcome you!");
return "index";
}
}

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接