Thymeleaf入门

Thymeleaf 是一个现代化的、服务端的Java模板引擎。

1、新建Spring项目:demo7,增加依赖:Spring Web、Spring Configuration Processor、Lombok、Thymeleaf 。自动生成的pom.xml如下。

<dependencies>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-thymeleaf</artifactId>
       </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>

       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-configuration-processor</artifactId>
           <optional>true</optional>
       </dependency>
       <dependency>
           <groupId>org.projectlombok</groupId>
           <artifactId>lombok</artifactId>
           <optional>true</optional>
       </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-test</artifactId>
           <scope>test</scope>
       </dependency>
</dependencies>

2、 ThymeleafAutoConfiguration

1)@EnableConfigurationProperties(ThymeleafProperties.class),Thymeleaf的所有配置值都在ThymeleafProperties里。

public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";

默认前缀是类路径下的templates目录,默认后缀是.html。

2)SpringResourceTemplateResolver defaultTemplateResolver(),配置模板解析器。
3)SpringTemplateEngine templateEngine(),配置模板引擎。
4)ThymeleafViewResolver thymeleafViewResolver(),配置视图解析器。

3、com.example.boot下新建控制器:controller.ViewController。

package com.example.boot.controller;

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

@Controller
public class ViewController {
    @GetMapping("/success")
    public String index(Model model){
        model.addAttribute("message","Hello,Thymeleaf");
        return "success";
    }
}

4、resources.templates下新建视图:index.html和success.html。

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<a href="/success">success</a>
</body>
</html>
<!-- success.html -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>success</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>

5、启动应用,点击链接,访问接口:localhost:8080/success。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值