【spirngboot3】借助thymeleaf渲染页面

  • Post author:
  • Post category:其他


引入thymeleaf依赖

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.3.1.RELEASE</version>
        </dependency>

配置application.properties

# templates文件夹的路径
spring.thymeleaf.prefix=classpath:/templates/
# templates中的所有文件后缀名,如/templates/main.html
spring.thymeleaf.suffix=.html
# 取消缓存方便开发时调试
spring.thymeleaf.cache=false
# js、css、图片等静态资源存放地址
spring.resources.static-locations=classpath:/static/

编写controller跳转类

@Controller
@RequestMapping("/main")
public class MianController {

    @RequestMapping("/page")
    public String page(Model model) {
        model.addAttribute("title","你好");
        return "main";
    }
}

在resources下新建templates文件夹,在templates下新建main.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script th:inline="javascript"> var ctx = [[@{/}]]; </script>
</head>
<body>
    <h1 th:text="${title}"></h1>
</body>
</html>

启动项目后,在浏览器输入

http://localhost:8080/main/page



版权声明:本文为u013808315原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。