Thymeleaf 简介和第一个Thymeleaf页面

Thymeleaf 简介

什么是Thymeleaf

Thymeleaf 是一个跟Velocity、FreeMarker类似的模板引擎,它可以完全替代JSP。相较与其他的模板引学,它有如下三个极吸引人的特点

  • Thymeleaf在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持html原型,然后在html标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释html时会忽略未定义的标签属性,所以thymeleaf的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
  • Thymeleaf 开箱即用的特性。它提供标准和Spring 标准两种方言,可以直接套用模板实现JSTL、OGNL表达式效果,避免每天套模板、改JSTL、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
  • Thymeleaf 提供Spring 标准方言和一个与SpringMVC完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
为什么需要Thymeleaf

如果希望以Jar形式发布模块则尽量不要使用JSP相关知识,这是因为JSP在内嵌的 Servlet 容器上运行有一些问题(内嵌Tomcat、Jetty 不支持Jar 形式运行JSP,Undertow不支持JSP)。
Spring Boot 中推荐使用Thymeleaf作为模板引擎,因为Thymeleaf提供了完美的Spring MVC支持,Spring Boot提供了大呈模板引擎,包括:

  • FreMarker
  • Groovy
  • Thymeleaf
  • Velocity
  • Beetl

第一个Thymeleaf页面

引入依赖

主要增加spring-boot-starter-thymeleaf和nekohtml这两个依赖

  • spring-boot-starter-thymeleaf:Thymeleaf自动配置
  • nekohtml:允许使用非严格的HTML语法
 <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/net.sourceforge.nekohtml/nekohtml -->
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.14</version>
        </dependency>

在这里插入图片描述

server:
  port: 8082
spring:
  application:
    name: hello-spring-boot
  thymeleaf:
    cache: false
    mode: HTML
    encoding: UTF-8
    servlet:
      content-type: text/html

在这里插入图片描述

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>第一个Thymeleaf页面</title>
</head>
<body>
    <span th:text="${name}">ww</span>
</body>
</html>

在这里插入图片描述

package com.kcbg.hellospringboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * @program: hello-spring-boot
 * @description: 第一个Thymeleaf页面
 * @author: MW
 * @create: 2020-06-12 21:44
 **/
@Controller
public class ThymeleafController {
    @GetMapping("/index")
    public String index(Model model){
        model.addAttribute("name","MW");
        return "index";
    }
}

在这里插入图片描述
启动项目访问
http://localhost:8082/index
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42222342/article/details/106723885