Spring Boot使用Thymeleaf

配置

  1. 如果创建项目的时候没有选择Thymeleaf模板,可以在pom.xml中添加Spring Boot专属Thymeleaf的大包依赖
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
  1. 使用Thymeleaf代替JSP,配置原理和JSP的视图解析器一样。只是Spring Boot的已整合实现xml配置,只需要在application.properties全局资源文件配置下即可即插即用。
# thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
spring.thymeleaf.cache=false
  1. 基本目录
    Spring Boot使用Thymeleaf_第1张图片

使用

  1. templates目录下新建一个简单的HTML文件


<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    
    <p th:text="'hello, ' + ${name}"/>
body>
html>

注意:text="'hello, ’ + ${name}",外用双引号,内用单引号,返过来无法识别

  1. 控制器
package xyz.cglzwz.demo.controller;

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

@Controller
public class TestController {
    @RequestMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("name", "chgl16");
        return "hello";
    }
}

注意:别使用@RestController,这样是返回JSON。就不能解析到视图hello.html了。
此外,每次运行crtl + z只是挂起进程,端口任然占用,切记exit。或者直接使用crtl + c强制结束。

你可能感兴趣的:(Spring,Boot,Thymeleaf)