1.新建spring boot项目,在pom.xml中添加thymeleaf依赖

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

2.在controller中添加方法success(),设置携带的数据,并实现跳转功能

此处的原理是:thymeleaf会将返回的字串拼接.html,并在templates下寻找页面资源

@Controller
public class HelloController {
    @RequestMapping("/success")
    public String success(Map<String, Object>map){
        map.put("hello", "你好");
        return "success";
    }
}

3.在templates下新建success.html页面,导入thymeleaf的命名空间,使用th:text语法显示数据

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
成功!
<div th:text="${hello}"></div>
</body>
</html>

可能遇到的问题,导入thymeleaf依赖出现版本问题,建议直接新建spring boot项目时,在模板引擎中勾选thymeleaf.

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐