springboot2学习记录之 整合thymeleaf

1.引入依赖

在pom.xml中dependencies标签中引用

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

2.设置默认前缀路径

首先我们在项目中先找到或者创建一个配置文件(.yml,.properties),这里以.properties为例:

在controller控制器中我们要返回很多页面,这些页面的前缀大多数都是相同的。

我们现在有这样一个需求:

在A文件夹下有三个文件A1,A2,A3。A1中有A1.html,A2中有A2.html,A3中有A3.html。

我们要在控制器中返回A1.html则要写成A/A1/A1.html,A2.html则要写成A/A2/A2.html,A3.html则要写成A/A3/A3.html。

我们发现他们都是存在A文件夹下:

则我们在之前创建的配置文件中就可以这样写了:

spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=utf-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.cache=false(缓存要关闭,要不然有时候会看不到我们想要的东西)
spring.thymeleaf.prefix=classpath:/A/
spring.thymeleaf.suffix=.html

基于上面的配置我们就可以编写我们的Controller了。(项目中如果不改变项目结构目录使用默认配置即可。)

3.编写Controller

我们要返回A1文件夹下的A1.html

    @RequestMapping("")  
    public ModelAndView index(){  
        return new ModelAndView("A1/A1.html");  
    }  

这样我们就一个最基本的thymeleaf就整合完了。






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 可以很方便的集成 Thymeleaf 模板引擎,下面是整合步骤: 1.添加 Thymeleaf 依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 2.配置 Thymeleaf 模板 在 `src/main/resources/templates/` 目录下创建一个 thymeleaf 模板文件,例如 index.html: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Thymeleaf Demo</title> </head> <body> <h1 th:text="${message}">Hello World!</h1> </body> </html> ``` 其中 `${message}` 表示从后台传递过来的数据。 3.配置视图解析器 在 application.properties 或 application.yml 文件中添加以下配置: ```yaml spring: thymeleaf: cache: false prefix: classpath:/templates/ suffix: .html encoding: utf-8 ``` 其中: - `cache` 表示是否开启缓存 - `prefix` 表示模板文件所在目录 - `suffix` 表示模板文件后缀 - `encoding` 表示模板文件编码 4.在 Controller 中使用 Thymeleaf 在 Controller 中设置需要传递到前端的数据,并指定要返回的模板文件名: ```java @Controller public class DemoController { @GetMapping("/hello") public String hello(Model model) { model.addAttribute("message", "Hello, Thymeleaf!"); return "index"; } } ``` 其中: - `@Controller` 表示这是一个控制器 - `@GetMapping("/hello")` 表示处理 GET 请求,路径为 /hello - `Model` 用于存储需要传递到前端的数据 - `return "index"` 表示返回名为 index 的模板文件 5.运行项目 启动 Spring Boot 项目,访问 http://localhost:8080/hello 即可看到效果。 以上就是 Spring Boot 整合 Thymeleaf 的基本步骤,希望能对你有所帮助。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值