zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    使用slf4j取代Apache Commons Logging
    IntelliJ远程调试教程
    java日志,(commons-loging 、log4j 、slf4j 、LogBack介绍)
    oracle 时间函数
    在Windows操作系统中,如何终止占有的8080端口的tomcat进程
    解决dwr报错【 Error: java.lang.SecurityException: No class by name: service】
    eclipse下使用tomcat启动maven项目
    Eclipse Java注释模板设置详解
    weblogic启动时日志重定向(nohup.out)
    信息化的基本概念
  • 原文地址:https://www.cnblogs.com/jinjiyese153/p/8566130.html
Copyright © 2011-2022 走看看