SpringBoot引入模板引擎實現(xiàn)視圖解析
視圖解析
SpringBoot 不支持 JSP,需要引入第三方模板引擎進行技術進行頁面渲染
1. 視圖解析方式
轉發(fā)、重定向以及自定義視圖
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
因此我們只需要開發(fā)頁面
頁面開發(fā)規(guī)則 —— ThymeleafProperties.class
public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html";
規(guī)則解釋:
- 頁面放在 /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="www.atguigu.com" rel="external nofollow" rel="external nofollow" th:href="${link}" rel="external nofollow" >去百度</a> <!--$符直接取值當成訪問路徑-->
<a href="www.atguigu.com" rel="external nofollow" rel="external nofollow" th:href="@{/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 中的數(shù)據(jù)會被放到請求域中
model.addAttribute("msg", "要好好學鴨~");
model.addAttribute("link","https://www.baidu.com/");
return "success"; // 轉發(fā)到 success.html (不寫后綴)
}
}訪問 http://localhost:8080/haha 可以看到 thymeleaf 自動幫我們渲染好的頁面

到此這篇關于SpringBoot引入模板引擎實現(xiàn)視圖解析的文章就介紹到這了,更多相關SpringBoot視圖解析內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java動態(tài)替換properties文件中鍵值方式
這篇文章主要介紹了Java動態(tài)替換properties文件中鍵值方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08
MyBatis-Plus自定義SQL和復雜查詢的實現(xiàn)
MyBatis-Plus增強了MyBatis的功能,提供注解和XML兩種自定義SQL方式,支持復雜查詢如多表關聯(lián)、動態(tài)分頁等,通過注解如@Select、@Insert、@Update、@Delete實現(xiàn)CRUD操作,本文就來介紹一下,感興趣的可以了解一下2024-10-10
spring?cache注解@Cacheable緩存穿透詳解
這篇文章主要介紹了spring?cache注解@Cacheable緩存穿透詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
springboot3生成本地文件url的實現(xiàn)示例
本文主要介紹了springboot3生成本地文件url的實現(xiàn)示例,從而提供一種高效的文件管理方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-01-01
基于swagger參數(shù)與實體中參數(shù)不一致的原因分析
這篇文章主要介紹了基于swagger參數(shù)與實體中參數(shù)不一致的原因分析,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11

