zoukankan      html  css  js  c++  java
  • 10 springboot的thymeleaf模板引擎

    springboot的thymeleaf模板引擎

    概念

    模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。

    比如JSP就是一个模板引擎,jsp通过 java 结合 html最后生成一个网页,模板引擎的思想都是一样的,都由 模板 + 数据 经过模板引擎渲染 最后 变成网页 ,如下图:

    image-20200831234659280

    为什么要使用thymeleaf模板引擎呢,因为springboot默认不支持jsp。具体原因:如果希望以 Jar 形式发布模块则尽量不要使用 JSP 相关知识,这是因为 JSP 在内嵌的 Servlet 容器上运行有一些问题 (内嵌 Tomcat、 Jetty 不支持 Jar 形式运行 JSP,Undertow 不支持 JSP)。所以就使用了thymeleaf,因为thymeleaf上手容易。

    引入thymeleaf依赖

    在springboot的pom文件中,引入下面的依赖就完成了thymeleaf的导入。

    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-java8time</artifactId>
    </dependency>
    

    使用thymeleaf

    那么如何使用thymeleaf呢 ? 我们进入到thymeleaf的配置类(ThymeleafProperties)去寻找使用方法,如下图:

    image-20200901000645449

    可以发现thymeleaf定义了前缀是模板文件存储的路径,后缀是模板的文件类型,这个是视图解析器的配置,springMVC里面的内容。表示:在控制器那里只需返回html的文件名即可,类型和文件夹路径不用填写,例子如下:

    随便在templates文件夹下建立一个名为test.html的文件,这个html文件名字必须和下面test()方法返回值的名字一致。否则通过controller映射不到templates文件夹下的test.html文件。

    controller层:

    @Controller
    public class TestView {
    
        @RequestMapping("/test")
        public String test(){
            return "test";
        }
    }
    

    浏览器访问如下图:image-20200901002119628

    可以发现直接访问映射路径test,可以直接访问到test.html文件。

    上面的都是简单应用,接下来真正使用了thymeleaf,thymeleaf使用文档,要想使用thymeleaf,首先在html文件头部是引入thymeleaf的命名空间,示例如下:

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

    controller层里面赋值:

    @Controller
    public class TestView {
    
        @RequestMapping("/test")
        public String test(Model mode){
            mode.addAttribute("msg","获取到的值就是这个");
            return "test";
        }
    }
    

    test.html前端页面取值:

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <!-- 适配手机 -->
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <!-- 指定IE使用的内核 -->
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Title</title>
    </head>
    <body>
    <!--    msg是controller那边赋值的变量, ${}是取值形式-->
       <div th:text="${msg}"></div>
    </body>
    </html>
    

    补充:输入th标签时,如果没有提示,应该是插件没有打开,setting - plugins - 搜索thymeleaf - 然后打勾。

    浏览器访问test映射路径:

    image-20200901093204474

    可以发现,controller那边的数据,test.html页面这边通过 th:text标签获取到。

    还有很多thymeleaf的标签没有使用,可以去这里thymeleaf使用文档去查看用法,这里就不过多展示,现在都流行前后端分离。

  • 相关阅读:
    排序应用于链表
    线性时间排序算法
    排序算法
    2017计蒜客蓝桥杯模拟赛5
    第六届河南省赛 River Crossing 简单DP
    POJ 3061 Subsequence 尺取法 POJ 3320 Jessica's Reading Problem map+set+尺取法
    天梯赛 L2-020. 功夫传人 BFS
    天梯赛 L2-019. 悄悄关注 map
    配置在Chrome,Firefox中打开
    http响应状态码大全
  • 原文地址:https://www.cnblogs.com/unlasting/p/13594421.html
Copyright © 2011-2022 走看看