在SpringBoot當(dāng)中使用Thymeleaf視圖解析器的詳細(xì)教程
在Spring Boot 當(dāng)中使用 Thymeleaf 視圖解析器
想要在 Spring Boot 當(dāng)中使用 Thymeleaf 視圖,就需要導(dǎo)入相關(guān)的 jar 依賴。在 pom.xml 文件中配置。

<!-- 引入 thymeleaf-start ,項(xiàng)目會(huì)自動(dòng)完成配置,-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在 Spring Boot當(dāng)中的 Thymeleaf 相關(guān)的類是 :ThymeleafProperties.java 類。

注意:路徑不可以隨便改,要按照要求來,或者通過 application.yaml 進(jìn)行修改。

spring:
thymeleaf:
prefix: "classpath:/填寫自己想要的路徑目錄"
# classpath:/ 類路徑起手
對應(yīng) HTML頁面上想要使用上 Thymeleaf 語法的需要加上如下的一行內(nèi)容,才行。

<html lang="en" xmlns:th="http://www.thymeleaf.org">
案例舉例:
在 pom.xml 文件當(dāng)中,導(dǎo)入相關(guān)的 jar 包文件。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.rainbowsea</groupId>
<artifactId>springboot_usersys</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 導(dǎo)入SpringBoot 父工程-規(guī)定寫法-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
</parent>
<!-- 導(dǎo)入web項(xiàng)目場景啟動(dòng)器:會(huì)自動(dòng)導(dǎo)入和web開發(fā)相關(guān)的jar包所有依賴【庫/jar】-->
<!-- 后面還會(huì)在說明spring-boot-starter-web 到底引入哪些相關(guān)依賴-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--引入lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- 引入 thymeleaf-start ,項(xiàng)目會(huì)自動(dòng)完成配置,-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 引入 lombok 插件 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
編寫相關(guān)項(xiàng)目的啟動(dòng)場景。

package com.rainbowsea.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // 項(xiàng)目啟動(dòng)標(biāo)志
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
對應(yīng)的 Bean 類

package com.rainbowsea.springboot.bean;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor // 無參數(shù)
public class Admin {
private String name;
private String password;
}
package com.rainbowsea.springboot.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor // 無參數(shù)
@AllArgsConstructor // 全參數(shù)
public class User {
private Integer id;
private String name;
private String password;
private Integer age;
private String email;
}
編寫相關(guān) thymeleaf 視圖,HTML文件。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>管理后臺(tái)</title>
</head>
<body>
<a href="#" rel="external nofollow" rel="external nofollow" >返回管理界面</a> <a href="#" rel="external nofollow" rel="external nofollow" >安全推出</a>
<hr>
<div style="text-align: center">
<h1>管理員</h1>
<table border="1px" cellspacing="0" bordercolor="green" style="text-align: center">
<tr bgcolor="pink">
<td>id</td>
<td>name</td>
<td>pwd</td>
<td>email</td>
<td>age</td>
</tr>
<tr bgcolor="#7fffd4" style="text-align: center" th:each="user:${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.password}"></td>
<td th:text="${user.email}"></td>
<td th:text="${user.age}"></td>
</tr>
</table>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<div style="text-align: center">
<h1>用戶登錄</h1>
<form action="#" th:action="@{/login}" method="post">
<label style="color: red" th:text="${msg}"></label><br>
用戶名: <input type="text" style="width: 150px" name="name"><br>
密碼: <input type="password" style="width: 150px" name="password"><br>
<input type="submit" value="登錄"><br>
<input type="reset" value="重新填寫"><br>
</form>
</div>
</body>
</html>
相關(guān)的 controller 控制器,處理請求內(nèi)容。
package com.rainbowsea.springboot.controller;
import com.rainbowsea.springboot.bean.Admin;
import com.rainbowsea.springboot.bean.User;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import javax.jws.WebParam;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
@Controller
public class AdminController {
@PostMapping("/login")
public String login(Admin admin, HttpSession session, Model model) {
// 驗(yàn)證用戶是否合法
if(StringUtils.hasText(admin.getName()) && "666".equals(admin.getPassword())) {
// 將登錄用戶保險(xiǎn)到 session會(huì)話域當(dāng)中
session.setAttribute("loginAdmin",admin);
// 合法,重定向到manage.html
// 請小伙伴回憶,Java web ,不使用請求轉(zhuǎn)發(fā)是防止刷新頁面會(huì)重復(fù)提交
// 這里老師為什么寫的是 manage.html,因?yàn)檫@樣可以更加明確的表示到哪個(gè)頁面
// manage.html 表示要去找方法的映射路徑為: manage.html
return "redirect:/manage.html";
} else {
// 不合法,就重新登錄,請求轉(zhuǎn)發(fā)
model.addAttribute("msg","賬號(hào)/用戶錯(cuò)誤");
return "adminLogin"; // 視圖解析
}
}
// 處理用戶的請求到 manage.html
// 是重定向——>get
@GetMapping("/manage.html")
public String mainPage(Model model,HttpSession session){
// 可以這里集合~模板數(shù)據(jù),放入到request域中,并顯示
ArrayList<User> users = new ArrayList<>();
users.add(new User(1,"關(guān)羽","666",28,"gy@ohu.com"));
users.add(new User(2,"關(guān)羽","666",28,"gy@ohu.com"));
users.add(new User(3,"關(guān)羽","666",28,"gy@ohu.com"));
users.add(new User(4,"關(guān)羽","666",28,"gy@ohu.com"));
users.add(new User(5,"關(guān)羽","666",28,"gy@ohu.com"));
model.addAttribute("users",users); // 放入到請求域當(dāng)中
return "manage"; // 視圖解析器
// 攔截器處理
// 獲取到 session會(huì)話域當(dāng)中的信息,判斷用戶是否登錄過,進(jìn)行一個(gè)過濾
/*Object loginAdmin = session.getAttribute("loginAdmin");
if(null != loginAdmin) { // 說明成功登錄過
// 可以這里集合~模板數(shù)據(jù),放入到request域中,并顯示
ArrayList<User> users = new ArrayList<>();
users.add(new User(1,"關(guān)羽","666",28,"gy@ohu.com"));
users.add(new User(2,"關(guān)羽","666",28,"gy@ohu.com"));
users.add(new User(3,"關(guān)羽","666",28,"gy@ohu.com"));
users.add(new User(4,"關(guān)羽","666",28,"gy@ohu.com"));
users.add(new User(5,"關(guān)羽","666",28,"gy@ohu.com"));
model.addAttribute("users",users); // 放入到請求域當(dāng)中
return "manage"; // 視圖解析器
} else {
// 說明沒有登錄過,
// 這里就返回登錄頁,并給出提示
model.addAttribute("msg","你沒有登錄/請登錄"); // 請求域
return "adminLogin"; // 請求轉(zhuǎn)發(fā)到 adminLogin.html視圖解析
}*/
}
}
package com.rainbowsea.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
// 編寫方法,轉(zhuǎn)發(fā)到登錄頁面
/*
解釋:
1.因?yàn)槲覀円肓?starter-thymeleaf
2.這里就會(huì)直接使用視圖解析到thymeleaf下的模板文件admin
*/
@GetMapping(value = {"/","/login"})
public String login(){
return "adminLogin";
}
}
配置的相關(guān)攔截器:

package com.rainbowsea.springboot.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 為了讓大家看到訪問的URI
String requestURI = request.getRequestURI();
String requestURL = request.getRequestURL().toString();
log.info("preHandle 攔截到的請求URI={}", requestURI);
log.info("preHandle 攔截到的請求URL={}", requestURL);
// 進(jìn)行登錄的校驗(yàn)
HttpSession session = request.getSession();
Object loginAdmin = session.getAttribute("loginAdmin");
if (null != loginAdmin) { // 說明該用戶已經(jīng)成功登錄
// 返回 true 就是放行
return true;
} else {
// 攔截,重新返回到登錄頁面
request.setAttribute("msg", "你沒有登錄/請登錄~~~");
// 注意:因?yàn)檫@里我們只有一個(gè)內(nèi)容被攔截了,而且該內(nèi)容的 uri路徑就是我們要跳轉(zhuǎn)進(jìn)入的路徑
request.getRequestDispatcher("/").forward(request, response); // 重定向
return false; // 攔截了,不放行
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("postHandle執(zhí)行了...");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("afterCompletion執(zhí)行了...");
}
}
// HandlerInterceptor

package com.rainbowsea.springboot.config;
import com.rainbowsea.springboot.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration // 配置攔截器
public class WebConfig
/* implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注冊自定義攔截器LoginInterceptor
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**") // 攔截所有的請求
.excludePathPatterns("/","/login","/images/**"); // 還要放行視圖的內(nèi)容,因?yàn)樯厦媸?
// 攔截所有,注意不要: templates ,因?yàn)閟prinboot的默認(rèn)配置,就是以templates為根路徑往下找的
// 所以添加就錯(cuò)了,就成了 /templates/templates/images/**了。
}*/
{
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
System.out.println("addInterceptors~~~");
// 注冊攔截器
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/","/login","/images/**");
}
};
}
}
啟動(dòng)程序,打開瀏覽器運(yùn)行測試

最后:
以上就是在SpringBoot當(dāng)中使用Thymeleaf視圖解析器的詳細(xì)教程的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot使用Thymeleaf的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
IntelliJ IDEA2020.1版本更新pom文件自動(dòng)導(dǎo)包的方法
這篇文章主要介紹了IntelliJ IDEA2020.1版本更新pom文件自動(dòng)導(dǎo)包的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
Java利用POI實(shí)現(xiàn)導(dǎo)入導(dǎo)出Excel表格示例代碼
最近工作中遇到一個(gè)需求,是需要導(dǎo)出數(shù)據(jù)到Excel表格里,所以寫個(gè)Demo測試一下,還是比較簡單的,現(xiàn)在分享給大家,有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-10-10
SpringCloud 服務(wù)注冊IP錯(cuò)誤的解決
這篇文章主要介紹了SpringCloud 服務(wù)注冊IP錯(cuò)誤的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
java 序列化對象 serializable 讀寫數(shù)據(jù)的實(shí)例
java 序列化對象 serializable 讀寫數(shù)據(jù)的實(shí)例,需要的朋友可以參考一下2013-03-03
FactoryBean?BeanFactory方法使用示例詳解講解
這篇文章主要為大家介紹了FactoryBean?BeanFactory方法使用示例詳解講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
SpringBoot實(shí)現(xiàn)阿里云短信接口對接的示例代碼
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)阿里云短信接口對接的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
Java中通過繼承Thread類創(chuàng)建線程的步驟
本文介紹了如何通過繼承Thread類創(chuàng)建線程,包括Thread類的定義、創(chuàng)建線程的步驟、優(yōu)缺點(diǎn)、使用場景和注意事項(xiàng),通過示例代碼展示了多線程下載文件的實(shí)現(xiàn),感興趣的朋友跟隨小編一起看看吧2025-02-02

