首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >SpringBoot之SpringBoot整合Thymeleaf模板引擎

SpringBoot之SpringBoot整合Thymeleaf模板引擎

作者头像
彼岸舞
发布2021-01-26 14:36:05
发布2021-01-26 14:36:05
4560
举报

SpringBoot之SpringBoot整合Thymeleaf模板引擎

添加Thymeleaf场景启动器

代码语言:javascript
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

编写控制器代码

  如果之前有引入过别的模板引擎,可以先注释掉,防止出现冲突什么的一些不明错误

  新增一个Thymeleaf的控制器

  ThymeleafIndexController.java

代码语言:javascript
复制
package com.springboot.demo.controller;

import com.springboot.demo.model.Flower;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

/**
 * @author ZYGisComputer
 */
@Controller
public class ThymeleafIndexController {

    @Autowired
    private Flower flower;
    
    @RequestMapping("/thymeleaf")
    public String thymeleafIndex(Map<String,Object> result){
        result.put("flower",flower);
        return "thymeleaf";
    }

}

  注意:不明白Flower的可以看一下《SpringBoot之读取配置文件中自定义的值》,这次放入一个对象进去

编写模板

  为了防止向上次整合FreeMarker翻车,这次配置一下Thymeleaf的一些信息

  在application.yml中配置Thymeleaf的配置

代码语言:javascript
复制
spring:
  thymeleaf:
    #prefix:指定模板所在的目录
    prefix: classpath:/templates/
    #check-tempate-location: 检查模板路径是否存在
    check-template-location: true
    #cache: 是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。
    cache: false
    #suffix 配置模板后缀名
    suffix: .html
    encoding: UTF-8
    mode: HTML5

这次直接指定为.html不再翻车

在templates文件夹下创建thymeleaf.html文件

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    姓名:<span th:text="${flower.getName()}"></span>
    年龄:<span th:text="${flower.getAge()}"></span>
</body>
</html>

注意:其中在 html标签上增加了 命名空间 xmlns:th="http://www.thymeleaf.org" 然后在下面就能写Thymeleaf的语法了

启动项目访问一下:

  希望不翻车..

  一举成功..舒服

作者:彼岸舞

时间:2021\01\21

内容关于:SpringBoot

本文来源于网络,只做技术分享,一概不负任何责任

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-01-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • SpringBoot之SpringBoot整合Thymeleaf模板引擎
    • 添加Thymeleaf场景启动器
    • 编写控制器代码
    • 编写模板
    • 启动项目访问一下:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档