寫在前面:
根據(jù)之前介紹的,Spring Boot Web項目創(chuàng)建步驟:
創(chuàng)建Spring Boot應(yīng)用巢价,選中我們項目中需要的模塊
項目創(chuàng)建完后鸦做,其基礎(chǔ)配置就已經(jīng)完成,我們只需要在配置文件(application.yml)中指定少量的配置就可以運行
業(yè)務(wù)代碼編寫
一造壮、SpringBoot對靜態(tài)資源的映射
1)在Spring Boot中我們將所有的前端使用的類庫,如:jQuery等 webjars骂束,以jar包的方式放在pom.xml文件中耳璧,自動引入依賴,如:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>
webjars地址: https://www.webjars.org/
Spring Boot源碼會依據(jù)類文件下的目錄訪問對應(yīng)的文件
classpath:/META-INF/resources/webjars/
這里想要詳細(xì)了解可以看源碼中 WebMvcAutoConfiguration類
訪問方式:
啟動Spring Boot, 訪問url:http://localhost:8080/webjars/jquery/3.4.1/jquery.js
2)如何訪問自定義頁面
通過查看Spring Boot的底層代碼WebMvcAutoConfiguration類展箱,得知自定義頁面旨枯,可以存放在,以下文件夾下混驰,即類路徑下的文件夾攀隔,通過訪問http://localhost:8080/dasda.html 即可皂贩,不需要我們關(guān)心,Springboot會自動去查找dasda.html頁面昆汹。
private static final String[] CLASSPATH_RESOURCE_LOCATIONS =
new String[]{
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"};
3)Spring Boot自定義首頁
歡迎頁明刷;靜態(tài)資源文件夾下的所有index.html頁面;被"/**"映射满粗;
源碼:
private Resource getIndexHtml(String location) {
return this.resourceLoader.getResource(location + "index.html");
}
在不要求訪問哪個頁面時辈末,自定掃描是否含有index.html, 有就會直接訪問index頁面。
二败潦、模板引擎
SpringBoot推薦的Thymeleaf本冲;
語法簡單,功能強(qiáng)大劫扒;
我們也可以在創(chuàng)建項目的時候選擇Thymeleaf模塊
1檬洞、引入thymeleaf;
1)引入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>3.0.9.RELEASE</version>
</dependency>
2沟饥、Thymeleaf使用
@ConfigurationProperties(
prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/";
private String suffix = ".html";
private String mode = "HTML";
private Charset encoding;
只要我們把HTML頁面放在classpath:/templates/添怔,thymeleaf就能自動渲染;
使用:
1)導(dǎo)入thymeleaf的名稱空間
<html lang="en" xmlns:th="http://www.thymeleaf.org">
2)使用thymeleaf語法贤旷;
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>展示</h1>
姓名:<span th:text="${name}"></span>
口頭語:<span th:text="${say}"></span>
</body>
</html>
3)controller層
@Controller
public class UserController {
@RequestMapping(value = "user")
public String UserContext(Map<String,String> user){
user.put("name","黃曉明");
user.put("say","我不要你覺得广料,我要我覺得");
return "user";
}
}
結(jié)果展示:
url: http://localhost:8080/user
3、語法規(guī)則
th:text幼驶;改變當(dāng)前元素里面的文本內(nèi)容艾杏;
th:任意html屬性;來替換原生屬性的值
下圖顯示其他對應(yīng)jsp標(biāo)簽