zoukankan      html  css  js  c++  java
  • 九、SpringBoot集成Thymeleaf模板引擎

    Thymeleaf咋读!???

    呵呵,是不是一脸懵逼。。。哥用我的大学四级英文知识告诉你吧:[θaimlif]。

    啥玩意?不会音标?...那你就这样叫它吧:“赛母李府”,大部分中国人是听不出破绽的。。。。

    Thymeleaf是啥?

    四个字:页面模板(有道翻译结果)

    就是在页面里面导入一些特有的标签和表达式,帮助我们更好地渲染页面

    个人理解:

    Thyme:百里香。leaf:叶子;

    百里香是啥玩意?

    经过上面的观察和分析,我感觉Thymeleaf的创作者是一个很有“生活”的人,我们看到上面图片上的百里香,一片一片的鲜翠的叶子很和谐的长在不同的枝头就好比我们的一个个HTML“叶面”分别存放在不同的文件夹下面,她们虽然在不同的枝头,但是她们的模样都很相似,这些相似点就是模板。。。

    好了,哥敢用哥的一包花生米和一瓶啤酒打赌!!!如果你有幸阅读到哥的这篇文章,那么这绝逼是你见过对Thymeleaf最最最牛X的介绍。。。

    官方介绍:https://www.thymeleaf.org/

    Thymeleaf能够处理HTML,XML,JavaScript,CSS甚至纯文本。

    看了上面的官方解释是不是更是一脸懵逼。。。那就不要纠结了,我们下面直接看她到底怎么用,用来干什么,这样你不就知道Thymeleaf是啥了吗

    SpringBoot集成Thymeleaf:

    首先为了大家看的不懵逼,我先展开一下整体项目结构:

    1、pom.xml 添加 Thymeleaf 模板引擎

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

    2、application.properties 配置 Thymeleaf 信息

    #下面是thymeleaf配置
    # 启用缓存:建议生产开启
    spring.thymeleaf.cache=false
    # 建议模版是否存在
    spring.thymeleaf.check-template-location=true
    # Content-Type 值
    spring.thymeleaf.servlet.content-type=text/html
    # 是否启用
    spring.thymeleaf.enabled=true
    # 模版编码
    spring.thymeleaf.encoding=utf-8
    # 应该从解析中排除的视图名称列表(用逗号分隔)
    spring.thymeleaf.excluded-view-names=
    # 模版模式
    spring.thymeleaf.mode=HTML5
    # 模版存放路径
    spring.thymeleaf.prefix=classpath:/templates/
    # 模版后缀
    spring.thymeleaf.suffix=.html

    3、创建controller类,编写代码

     我们创建ThymeleafTest.java,代码如下:

    @Controller
    @RequestMapping("/thymeleafTest")
    public class ThymeleafTest {
        @RequestMapping("/testThymeleaf")
        public ModelAndView testThymeleaf(){
            ModelAndView modelAndView=new ModelAndView("/thymeleaf");
            modelAndView.addObject("user","任正非");
            return modelAndView;
        }
    }

    4、 创建模板,编写html代码

    我们在resources/templates下创建index.html,代码如下:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>thymeleaf测试页面</title>
    </head>
    <body>
    <h1 th:text="${user}"></h1>
    </body>
    </html>

     启动项目然后访问:

    至此thymeleaf就成功集成了,是不是很开心。。呵呵,但是你别高兴的太早了,,,此时你会发现你之前配置成功的JSP页面现在不能访问了

    关于这个问题的解决请参考鄙人的另一篇博客:

    https://www.cnblogs.com/luzhanshi/p/10925851.html

  • 相关阅读:
    [洛谷P4774] [NOI2018]屠龙勇士
    [洛谷P3338] [ZJOI2014]力
    [洛谷P1707] 刷题比赛
    svn查看指定版本提交信息的命令
    ajax无刷新上传文件
    给docker里的php安装gd扩展
    PHP基于openssl实现的非对称加密操作
    php获取文件扩展名
    javascript格式化日期
    javascript获取url参数
  • 原文地址:https://www.cnblogs.com/luzhanshi/p/10928501.html
Copyright © 2011-2022 走看看