7、SpringBoot 使用 thymeleaf

SpringBoot 使用 thymeleaf

步骤一:在pom.xml中引入thymeleaf

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

关闭thymeleaf缓存

开发过程中建议关闭缓存

spring:
  thymeleaf:
    cache: false

编写hello.html

放到resources/templates/

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>
        Hello thymeleaf!
        <br>
        My name is Nancy!
    </h1>
</body>
</html>

编写HelloController

package cn.ylx.controller;

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

@Controller
@RequestMapping("/templates")
public class HelloController {

    @RequestMapping("/hello")
    public String sayHello(){
        return "hello";
    }

}

浏览器请求 http://localhost:8080/templates/hello
会找到相应的servlet,返回hello,找到resources/templates/hello.html,返回页面。

编写模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>
        Hello thymeleaf!
        <br>
        My name is <span th:text="${name}"></span>!
    </h1>
</body>
</html>

编写访问模板文件Controller

package cn.ylx.controller;

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

import java.util.Map;

@Controller
@RequestMapping("/templates")
public class HelloController {

    @RequestMapping("/hello")
    public String sayHello(Map<String,Object> map){
        map.put("name", "Nancy");
        return "hello";
    }

}

测试:能成功渠道Nancy。

猜你喜欢

转载自blog.csdn.net/weixin_42112635/article/details/84721786