一起来学 SpringBoot 2.x | 第四篇:整合 Thymeleaf 模板

点击上方“芋道源码”,选择“置顶公众号”

技术文章第一时间送达!

源码精品专栏

 



摘要: 原创出处 http://blog.battcn.com/2018/04/28/springboot/v2-web-thymeleaf/ 「唐亚峰」欢迎转载,保留摘要,谢谢!

  • thymeleaf介绍

  • 使用

  • 小技巧

  • 默认配置

  • 总结

  • 说点什么


SpringBoot 是为了简化 Spring 应用的创建、运行、调试、部署等一系列问题而诞生的产物,自动装配的特性让我们可以更好的关注业务本身而不是外部的XML配置,我们只需遵循规范,引入相关的依赖就可以轻易的搭建出一个 WEB 工程

在前面几章中已经介绍了如何创建一个SpringBoot 项目,同时简单的描述了SpringBoot REST Web服务。除此之外它也是支持如JSPThymeleafFreeMarkerMustacheVelocity 等各种模板引擎,同时还为开发者提供了自定义模板扩展的支持。

使用嵌入式Servlet容器时,请避免使用JSP,因为使用JSP打包后会存在一些限制。

SpringBoot使用上述模板,默认从 src/main/resources/templates下加载。

thymeleaf介绍

Thymeleaf是现代化服务器端的Java模板引擎,不同与其它几种模板的是Thymeleaf的语法更加接近HTML,并且具有很高的扩展性。详细资料可以浏览官网。

特点

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

  • 开箱即用,为Spring提供方言,可直接套用模板实现JSTL、 OGNL表达式效果,避免每天因套用模板而修改JSTL、 OGNL标签的困扰。同时开发人员可以扩展自定义的方言。

  • SpringBoot官方推荐模板,提供了可选集成模块(spring-boot-starter-thymeleaf),可以快速的实现表单绑定、属性编辑器、国际化等功能。

使用

首先要在 pom.xml 中添加对 thymeleaf 模板依赖

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

然后创建一个 ThymeleafController 用来映射HTTP请求与页面的跳转,下面写了两种方式,第一种比较直观和优雅,第二种相对普遍且代码较少,且迎合从struts2跳坑的朋友们…

  • Spring4.3以后为简化@RequestMapping(method = RequestMethod.XXX)的写法,故而将其做了一层包装,也就是现在的GetMapping、PostMapping、PutMapping、DeleteMapping、PatchMapping

package com.battcn.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;

/**
 * @author Levin
 * @since 2018/4/23 0023
 */

@Controller
@RequestMapping
public class ThymeleafController {

    @GetMapping("/index")
    public ModelAndView index() {
        ModelAndView view = new ModelAndView();
        // 设置跳转的视图 默认映射到 src/main/resources/templates/{viewName}.html
        view.setViewName("index");
        // 设置属性
        view.addObject("title""我的第一个WEB页面");
        view.addObject("desc""欢迎进入battcn-web 系统");
        Author author = new Author();
        author.setAge(22);
        author.setEmail("[email protected]");
        author.setName("唐亚峰");
        view.addObject("author", author);
        return view;
    }

    @GetMapping("/index1")
    public String index1(HttpServletRequest request) {
        // TODO 与上面的写法不同,但是结果一致。
        // 设置属性
        request.setAttribute("title""我的第一个WEB页面");
        request.setAttribute("desc""欢迎进入battcn-web 系统");
        Author author = new Author();
        author.setAge(22);
        author.setEmail("[email protected]");
        author.setName("唐亚峰");
        request.setAttribute("author", author);
        // 返回的 index 默认映射到 src/main/resources/templates/xxxx.html
        return "index";
    }

    class Author {
        private int age;
        private String name;
        private String email;
        // 省略 get set
    }
}

最后在 src/main/resources/templates 目录下创建一个名 index.html 的模板文件,可以看到 thymeleaf 是通过在标签中添加额外属性动态绑定数据的

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

<head>
    <meta charset="UTF-8">
    <!-- 可以看到 thymeleaf 是通过在标签里添加额外属性来绑定动态数据的 -->
    <title th:text="${title}">Title</title>
    <!-- 在/resources/static/js目录下创建一个hello.js 用如下语法依赖即可-->
    <script type="text/javascript" th:src="@{/js/hello.js}"></script>
</head>
<body>
    <h1 th:text="${desc}">Hello World</h1>
    <h2>=====作者信息=====</h2>
        <p th:text="${author?.name}"></p>
        <p th:text="${author?.age}"></p>
        <p th:text="${author?.email}"></p>
</body>
</html>

静态效果

双击打开 index.html 既可以看到如下的静态效果,并未和其它模板一样显示一堆标签的内容,而是正常渲染静态页面


640静态效果


动态效果

在浏览器输入:http://localhost:8080/index 可以看到渲染后的效果,真正意义上的动静分离了


640动态效果


小技巧

模板热部署

在 IntelliJ IDEA 中使用 thymeleaf 模板的时候,发现每次修改静态页面都需要重启才生效,这点是很不友好的,百度了下发现原来是默认配置搞的鬼,为了提高响应速度,默认情况下会缓存模板。如果是在开发中请将spring.thymeleaf.cache 属性设置成 false。在每次修改静态内容时按Ctrl+Shift+F9即可重新加载了…

修改默认favicon.ico 图标

默认情况下使用springboot总能看到一片叶子,这是因为我们没配置自己的ico导致的,解决方法也很简单,只需要在src/main/static/目录下放置一张名为favicon.ico就可以了

默认配置

SpringBoot 默认情况下为我们做了如下的默认配置工作,熟悉默认配置在开发过程中可以更好的解决问题


640SpringBoot为thymeleaf模板提供的默认配置项


总结

Thymeleaf参考手册:https://blog.csdn.net/zrk1000/article/details/72667478

WEB MVC详细的内容请参考官方文档:https://docs.spring.io/spring/docs/5.0.5.RELEASE/spring-framework-reference/web.html#mvc

目前很多大佬都写过关于 SpringBoot 的教程了,如有雷同,请多多包涵,本教程基于最新的 spring-boot-starter-parent:2.0.1.RELEASE编写,包括新版本的特性都会一起介绍…

说点什么

全文代码:https://github.com/battcn/spring-boot2-learning/tree/master/chapter3

666. 彩蛋




如果你对 Dubbo 感兴趣,欢迎加入我的知识星球一起交流。

640?

知识星球



目前在知识星球(https://t.zsxq.com/2VbiaEu)更新了如下 Dubbo 源码解析如下:

01. 调试环境搭建
02. 项目结构一览
03. 配置 Configuration
04. 核心流程一览

05. 拓展机制 SPI

06. 线程池

07. 服务暴露 Export

08. 服务引用 Refer

09. 注册中心 Registry

10. 动态编译 Compile

11. 动态代理 Proxy

12. 服务调用 Invoke

13. 调用特性 

14. 过滤器 Filter

15. NIO 服务器

16. P2P 服务器

17. HTTP 服务器

18. 序列化 Serialization

19. 集群容错 Cluster

20. 优雅停机

21. 日志适配

22. 状态检查

23. 监控中心 Monitor

24. 管理中心 Admin

25. 运维命令 QOS

26. 链路追踪 Tracing

...
一共 60 篇++


源码不易↓↓↓

点赞支持老艿艿↓↓

猜你喜欢

转载自blog.csdn.net/x5fnncxzq4/article/details/81140302
今日推荐