SpringBoot使用Thymeleaf模板

首先导入依赖:

  1. <dependencies>
  2.   <!--web-->  <dependency>
  3.     <groupId>org.springframework.boot</groupId>
  4.     <artifactId>spring-boot-starter-web</artifactId>
  5.   </dependency>
  6.   <!--thymeleaf模板-->
  7.   <dependency>
  8.     <groupId>org.springframework.boot</groupId>
  9.     <artifactId>spring-boot-starter-thymeleaf</artifactId>
  10.   </dependency>
  11.   <!--test-->
  12.   <dependency>
  13.     <groupId>org.springframework.boot</groupId>
  14.     <artifactId>spring-boot-starter-test</artifactId>
  15.     <scope>test</scope>
  16.   </dependency>
  17. </dependencies>                 

默认配置:

不需要做任何配置,启动器已经把Thymeleaf的视图配置完成:

默认前缀:classpath:/templates

默认后缀:.html

所以如果需要返回视图:user,会指向到classpath:/templates/user.html

页面缓存:

Thymeleaf默认会开启页面缓存,提高页面并发能力。但会导致修改的页面不会立即被展现,需要重启才可以,因此需要关闭缓存:

  1. # 关闭Thymeleaf的缓存
  2. spring.thymeleaf.cache=false

另外,在idea中,修改完毕页面,需要使用快捷键:ctrl+shift+F9来刷新工程(即刷新修改过的页面)

快速开始:

新建一个controller,控制视图跳转:

  1. package com.leyou.page.web;
  2.  
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5.  
  6. @Controller
  7. public class HelloController {
  8.   @GetMapping("hello")
  9.   public String toHello() {
  10.     return "hello";// 普通字符串被当成视图名称,结果前缀和后缀查找视图
  11.   }
  12. }

新建一个html模板:

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4.   <meta charset="UTF-8">
  5.   <title>Hello</title>
  6. </head>
  7. <body>
  8.   <h1>
  9.     msg<span th:text="${msg}"></span>
  10.   </h1>
  11. </body>
  12. </html>

注意!!!需要把html的命名空间,加上:

  1. xmlns:th="http://www.thymeleaf.org"

否则不会有语法提示。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值