Spring Boot 学习 (七)springboot 集成 Thymeleaf 模板引擎

一、什么事是Thymeleaf

Thymeleaf 是面向 Web 和独立环境的现代服务器端 Java 模板引擎,能够处理 HTML、XML、JavaScript、CSS 甚至纯文本。Thymeleaf 主要有以下几个特点:

  • 有网络和无网络的状态下均可运行:

即前端可以查看页面的静态效果,后台可以查看带数据的动态页面,当有数据返回到页面时,Thymeleaf标签会动态地替换掉静态内容。

这是由于它支持Html原型,然后在HTML标签里增加额外的属性来表达模板+数据的展示方式。浏览器解释HTML时会忽略未定义的标签属性,所以Thymeleaf模板可以静态的运行;当数据返回到页面时,Thymeleaf标签会动态替换掉静态内容,使页面动态显示。

  • 开箱即用:

它提供标准和spring标准两种语言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的语言。

  • Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

二、SpringBoot 与 Thymeleaf 的集成

  • 在pom.xml中引入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring‐boot‐starter‐thymeleaf</artifactId>
</dependency>
  • 通过查看源码org\springframework\boot\autoconfigure\thymeleaf\ThymeleafProperties.class我们可以看到SpringBoot为我们默认配置了渲染html页面的路径:classpath:/templates/,只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染
package org.springframework.boot.autoconfigure.thymeleaf;
@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
  • 编写一个Controller:
package com.linco.springbootwebrestfulcrud.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.Controller;

import java.util.Map;

@Controller//注意这里不能用@RestController
public class ThymeleafController {

    @RequestMapping("/hello")
    public String helloThymeleaf(Map<String,String> map){

        map.put("hello","你好!");
        return "success";
    }
}
  • 在  类路径下新建文件夹templates并创建success.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Hello Thymeleaf</h1>
</body>
</html>
  • 启动应用,并访问localhost:8080/hello:可以看到返回页面的即是我们的HTML页面:

三、本篇文章不涉及Thymeleaf 的语法知识,有关Thymeleaf语法知识可以参考以下链接:

https://www.thymeleaf.org/documentation.html

谢谢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值