Thymeleaf 简介及入门

Thymeleaf 简介

  • Thymeleaf 是Web 和独立环境的现代服务器端Java模板引擎,能够处理HTML,XML,JavaScript,CSS 甚至纯文本。
  • Thymeleaf 的主要目标是提供一种优雅和高度可维护的创建模板的方式。为了实现这一点,它建立在自然模板的概念上,将其逻辑注入到模板文件中,不会影响模板被用作设计原型。这改善了设计的沟通,弥补了设计和开发团队之间的差距。
  • Thymeleaf 也从一开始就设计了Web标准 - 特别是HTML5 - 允许您创建完全验证的模板,Spring Boot 官方推荐使用 thymeleaf而不是JSP。
  • Thymeleaf 官网:https://www.thymeleaf.org/
  • Thymeleaf 在Github 的主页:https://github.com/thymeleaf/thymeleaf
  • 可以参考《Spring Boot 引入 Thymeleaf 及入门》

模板引擎

  • 市面上主流的 Java 模板引擎有:JSP、Velocity、Freemarker、Thymeleaf
  • JSP本质也是模板引擎,Spring Boot 官方推荐使用 “Thymeleaf”模板引擎
  • 模板引擎原理图如下,模板引擎的作用都是将模板(页面)和数据进行整合然后输出显示,区别在于不同的模板使用不同的语法,如JSP的JSTL表达式,已经JSP自己的表达式和语法,同理Thymeleaf也有自己的语法

官方文档下载

Hello World

  • 直接使用 Spring Boot 应用来学习 Thymeleaf所有语法知识,下面第一步就是新建 Spring Boot 项目,对于Spring Boot 不熟悉的可以参考《Spring Boot》

新建应用

		<!-- 导入Spring Boot的thymeleaf依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

后台控制器

package com.lct.controller;

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

import java.util.Map;

/**
 * Created by Administrator on 2018/7/17 0017.
 * 用户控制器
 */
@Controller
public class UserController {

    /**
     * 全部基于 Spring Boot给 Thymeleaf的默认配置
     * 所以下面会跳转到 classpath:/templates/home.html 页面
     *
     * @param paramMap
     * @return
     */
    @RequestMapping("home")
    public String goHome(Map<String, Object> paramMap) {
        /** 默认Map的内容会放大请求域中,页面可以直接使用Thymeleaf取值*/
        paramMap.put("name", "张三");
        paramMap.put("age", 35);
        return "home";
    }

}

前端页面

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>主页</title>
</head>
<body>
<h3>欢迎来到主页</h3>
    <!--Thymeleaf 语法取值-->
    姓名:<span th:text="${name}">未知</span>
    年龄:<span th:text="${age}">未知</span>
</body>
</html>

浏览器访问测试

猜你喜欢

转载自blog.csdn.net/wangmx1993328/article/details/81054474
今日推荐