• SpringBoot使用Thymeleaf模板


    © 版权声明:本文为博主原创文章,转载请注明出处

    Thymeleaf模板简介

      Thymeleaf模板是一个现代化的服务端java模板引擎对于所有的web和独立环境

      Thymeleaf的主要目标是为你的开发工作流程带来优雅自然的模板 ------ HTML能正确的显示在浏览器中,并且也可以作为静态原型工作,允许开发团队加强协作

      在有Spring框架的模块,与您最喜爱的工具的集成为一体,并能插入自己的功能,Thymeleaf是理想的现代化的HTML5 Web开发JVM ------ 虽然它可以做的更多

      摘自官网:http://www.thymeleaf.org/

      也是SpringBoot推荐使用的模板

    SpringBoot配置

    1. application.yml配置(application.properties同样)

    spring:
      thymeleaf:
        prefix: classpath:/templates/ # 必须以/结尾,否则报错找不到模板
        suffix: .html
        mode: HTML5
        encoding: UTF-8
        cache: false # 关闭缓存,即时刷新。上线后需改为true
        servlet:
          content-type: text/html

    2. 实现Controller

    package com.imooc.controller;
    
    import com.imooc.pojo.User;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    @RequestMapping("th")
    public class ThymeleafController {
    
        @GetMapping("/index")
        public String index(ModelMap map) {
            map.addAttribute("name", "thymeleaf-imooc");
            return "thymeleaf/index";
        }
    
        @GetMapping("/center")
        public String center() {
            return "thymeleaf/center/center";
        }
    
        @GetMapping("/test")
        public String test() {
            User user = new User();
            return "";
        }
    
    }

    3. 创建Thymeleaf模板

      3.1 index.html(位于 templates/thymeleaf/ 目录下)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        Thymeleaf模板引擎
        <h1 th:text="${name}">hello world</h1>
    </body>
    </html>

      3.2 center.html(位于 templates/thymeleaf/center/ 目录下)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        Thymeleaf模板引擎
        <h1>center page</h1>
    </body>
    </html>

    4. 启动SpringBoot项目,测试即可

    参考:

    https://www.imooc.com/video/16721

  • 相关阅读:
    网页中加入Flash的代码
    AJAX示例
    图片过滤效果
    ASP.NET性能优化
    什么是AJAX
    动态获取enum的值并且添到List中
    VSTO为Excel快捷菜单添加项
    OpenXML for office SDK 2.5 Download url.
    WebClient
    C#监控本地目录文件变化
  • 原文地址:https://www.cnblogs.com/jinjiyese153/p/8566130.html
Copyright © 2020-2023  润新知