springboot:springboot的web開發(靜態資源的處理方式、首頁和圖示定製、thymeleaf模板引擎初識)
阿新 • • 發佈:2020-09-13
1、靜態資源的處理方式
(1)依賴的方式
匯入依賴:
<dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.4.1</version> </dependency>
檢視jquery檔案位置,獲取jQuery檔案:
獲取jquery檔案成功:
(2)在目錄中書寫
檢視原始碼:
可以在resources目錄下建立三個目錄:
其中resources目錄下的優先順序最高,static其次,public最低
2、首頁和圖示定製
(1)原始碼
(2)首頁的書寫與訪問
在public、resources、static中的任意一個目錄放置首頁:
書寫首頁:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <h3>下午好,現在是2020年9月13日16:42:26</h3> </body> </html>
測試執行:
(3)圖示
先在配置檔案中關閉預設的圖示:
spring.mvc.favicon.enabled=false
匯入圖示:
3、thymeleaf模板引擎
(1)概念
springboot是不支援jsp的,如果我們直接用純靜態頁面,會給我們開發會帶來非常大的麻煩,SpringBoot推薦我們使用模板引擎。
(2)匯入依賴
<dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-java8time</artifactId> </dependency>
(3)在templates目錄下建立html頁面
(4)在controller層書寫程式碼跳轉到controller頁面
@Controller public class TestController { @RequestMapping("/test") public String hello(){ return "test"; } }
測試:
結論:只要需要使用thymeleaf,只需要匯入對應的依賴就可以了,我們將html放在我們的templates目錄下即可通過controller訪問到頁面
檢視原始碼:
(5)向模板寫入資料
書寫html格式的模板:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div th:text="${msg}"></div> </body> </html>
在controller層將資料寫入模板:
@Controller public class TestController { @RequestMapping("/test") public String hello(Model model){ model.addAttribute("msg","hello SpringBoot"); return "test"; } }
測試:
4、thymeleaf語法
(1)遍歷
資料:
@Controller public class TestController { @RequestMapping("/test") public String hello(Model model){ model.addAttribute("users", Arrays.asList("tom","jack","zhai")); return "test"; } }
模板:
<body> <h3 th:each="user:${users}" th:text="${user}"></h3> </body>
測試: