美文网首页推文上热门(千万赞三)
springboot2.x独门秘籍(四)thymeleaf整合

springboot2.x独门秘籍(四)thymeleaf整合

作者: 学知 | 来源:发表于2019-12-05 23:16 被阅读0次

    文 | 学者学者

    尊敬的读者朋友,本文是《springboot2.x独门秘籍》系列的第四篇,本专题的文章将会以springboot实战项目为切入点,系统化的学习全栈领域的核心技术,打造真全栈、真实力的全能型人才。专题讲解的过程中,均附带项目源代码,学完了你可以成功主导项目01过程。如需获取额外编程资料或源码,点击作者主页私信即可。


    开题寄语 IDEA整合
    走进spring大家庭 thymeleaf整合
    更多......

    在讲解thymeleaf整合前,我们先了解什么是前后端分离,什么是thymeleaf,以及它有什么好处。

    在传统的Java web项目开发中,html代码中会附带很多的jstl、el表达式,或者直接嵌套一段java代码构成jsp页面,这就是前后端不分离的情况,这样做虽然对部分开发人员是友好的,但是前后端耦合度太高,带来的是项目乱成一锅粥,出问题会出现前后端工程师互相踢皮球的情况。

    近年来,随着IT技术的不断发展,前后端分离已然成为了热门话题。最通俗的理解,前后端分离就是把数据的显示和数据的操作分离开来,前端 专注于数据的显示,后端专注于数据的操作,这样前后端耦合度降低,后端项目还可以分布式部署、集群部署。

    模板引擎就是专门为了前后端分离产生的,在模板引擎的加持下,前后端不仅可以实现代码分离,还可以实习数据分离、代码重用等,大大提高了开发效率。thymeleaf作为众多模板引擎中的一种,也是spring官方推崇的模板引擎,可以完全实现前后端分离,所以本篇文章就分享在springboot项目中如何整合并使用thymeleaf。



    【01】pom文件中添加依赖

          <!--thymeleaf依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
    
            <!--nekohtml,让thymeleaf格式要求更加友好-->
            <dependency>
                <groupId>net.sourceforge.nekohtml</groupId>
                <artifactId>nekohtml</artifactId>
                <version>1.9.22</version>
            </dependency>
    

    之所以要添加nekohtml的依赖,是因为thymeleaf默认对html的检查是非常严格的,少一个标签都会报错,添加nekohtml依赖后,nekohtml可以为我们补全缺少的标签,让thymeleaf的使用体验更加友好。

    【02】配置thymeleaf
    此处我以yml形式的配置文件给大家做说明,注释的部分代表这是thymeleaf的默认配置,如果没有变更的需要,则可以不写这些配置。如果对yml文件和properties文件不熟悉,可参考我以前写的文章,传送门

    spring:
      thymeleaf:
        mode: LEGACYHTML5
        encoding: UTF-8
        cache: false
        servlet:
          content-type: text/html
          #prefix: classpath:/templates/
          #suffix: .html
    

    上述配置中,mode的默认值是HTML,此时thymeleaf对HTML检查很严格,缺少标签会报错,改为LEGACYHTML5可以得到一个可能更友好亲切的格式要求

    cache缓存一定要关闭,要不然热更新会因为缓存的原因失效。编码格式encoding和content-type写明比较好,易于理解。

    至于映射路径的前缀prefix,默认映射到src/main/resources/templates目录下,后缀suffix默认是.html,可以不写。



    关于thymeleaf的使用,无非就是三种情况,一种是读取css、js、images等静态文件,第二种是html中读取后端传过来的值,可以进行遍历、替换等;第三种是js代码中进行内联表达式取值。

    下面我写一个例子,验证整合thymeleaf后,如何请求一个html页面、如何在页面中读取后端传过来的值,以及如何读取js、css等静态文件。
    【controller层】

    package cn.xzxz.xuezhi.controller;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    @Controller
    @RequestMapping("/index")
    public class IndexController {
        /**
         * html文件路径前缀
         */
        private String homePrefix="mobile/home/";
        @GetMapping("/")
        public String index(Model model) {
            model.addAttribute("value","this value come from system");
            return  homePrefix+"index";
        }
    }
    

    controller层中返回一个页面,该页面在mobile/home目录下,名字叫index,路径前缀是thymeleaf默认的src/main/resources/templates,后缀也是默认的.html。
    index.html文件如下:

    <!doctype html >
        <html lang="en"  xmlns="http://www.w3.org/1999/xhtml"
          xmlns:th="http://www.thymeleaf.org">
        <head>
            <th:block th:include="mobile/include::#header" />
            <title>学知</title>
        </head>
        <body>
            <div class="container" style="padding:50px 50px; height: 383px;background-color:#ccc;">
                <div class="btn btn-success">hello</div>
                <h2 th:text="${value}">静态页面显示的值</h2>
            </div>
        </body>
        <th:block th:replace="mobile/include::#footer" />
        <script>
            $(function(){
                alert("welcome to xuezhi!");
            });
        </script>
        </html>
    

    自定义头文件include.html如下

    <div id="header">
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" th:href="@{/css/mobile/common.css}">
        <link rel="stylesheet" th:href="@{/plugins/bootstrap-4.3.1/css/bootstrap.css}">
    </div>
    <div id="footer">
        <script th:line="javascript">
            var prefix=/*[[@{/}]]*/'static';
        </script>
        <script th:src="@{/plugins/jquery/jquery-3.4.1.js}"></script>
        <script th:src="@{/plugins/bootstrap-4.3.1/js/bootstrap.js}"></script>
    </div>
    

    如果thymeleaf整合是正确的,那么浏览器就可以正确解析页面,读取到后端传递过来的值,并且js、css都可以被正确引用。结果表明,按上述步骤整合,完全正确。




    除了上述的整合、配置、使用,关于thymeleaf还有一些零散知识点,比如常见的$、@、#、*代表什么,html头部的xmlns代表什么,meta标签有什么作用等。
    @主要用来读取js、css、images等,和th:src或者th:href配合使用,比如

    <!-- 读取图片 -->
    <img th:src="@{/images/mobile/thymeleaf.png}" alt="" >
    <!-- 读取css -->
    <link rel="stylesheet" th:href="@{/css/mobile/common.css}">
    <!-- 读取js -->
     <script th:src="@{/plugins/jquery/jquery-3.4.1.js}"></script>
    

    $可以和th:text配合读取值,比如

    <h2 th:text="${value}">静态页面显示的值</h2>
    

    #和thymeleaf的工具类配合使用,如 #strings

    *{}这个表达式,是获取指定的对象中的变量值。需要在前面指定对象,可以是集合中的某个对象,也可以是单独的一个对象。

    至于xmlns和meta标签,主要是给搜索引擎和浏览器看的,比如

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


    一如既往,期待您的真知灼见…,springboot2.x系列文章以及大厂内部资料将持续更新,如需获取资料或实战案例源码,欢迎点击我的主页或微信扫码呼叫,乐意为你解决开发中的疑难杂症。

    相关文章

      网友评论

        本文标题:springboot2.x独门秘籍(四)thymeleaf整合

        本文链接:https://www.haomeiwen.com/subject/hgujgctx.html