目录
- 视图解析
- 1. 视图解析方式
- 2. 使用
- 3. 原理
视图解析
SpringBoot 不支持 JSP,需要引入第三方模板引擎进行技术进行页面渲染
1. 视图解析方式
转发、重定向以及自定义视图
2. 使用
在 pom.xml 文件中引入 Starter
<!--导入Thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3. 原理
thymeleaf 自动配置类 —— ThymeleafAutoConfiguration.class
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {}
自动配好的策略:
(1)所有的配置值都在 ThymeleafProperties
(2)配好了 SpringTemplateEngine
(3)配好了 ThymeleafViewResolverConfiguration
因此我们只需要开发页面
页面开发规则 —— ThymeleafProperties.class
public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html";
规则解释:
- 页面放在 /templates/ 里
- 页面都是 .html
一个小 Demo:
HTML 端
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"> <!--重点一: 导入 thymeleaf-->
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${msg}">haha</h1> <!--通过th + $ 的方式取出值-->
<h2>
<a href="https://www.freexyz.cn/dev/www.atguigu.com" rel="external nofollow" rel="external nofollow" th:href="https://www.freexyz.cn/dev/${link}" rel="external nofollow" >去百度</a> <!--$符直接取值当成访问路径-->
<a href="https://www.freexyz.cn/dev/www.atguigu.com" rel="external nofollow" rel="external nofollow" th:href="https://www.freexyz.cn/dev/@{/link}" rel="external nofollow" >去百度</a> <!--@符拼接访问路径,自动加前置路径-->
</h2>
</body>
</html>
viewTestController 类
package com.example.demo2.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class viewTestController {
@GetMapping("/haha")
public String testhaha(Model model){
// model 中的数据会被放到请求域中
model.addAttribute("msg", "要好好学鸭~");
model.addAttribute("link","https://www.baidu.com/");
return "success"; // 转发到 success.html (不写后缀)
}
}
访问 http://localhost:8080/haha 可以看到 thymeleaf 自动帮我们渲染好的页面

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)