步驟 1 : 可運行項目
本知識點是建立在 上一個知識點 的基礎上進行的改進
首先下載一個簡單的可運行項目作為演示:網盤鏈接:http://t.cn/A6Al5mmq
下載后解壓,比如解壓到 E:\project\springboot 目錄下
步驟 2 : css 文件
在 webapp 目錄下新建 static/css 目錄,然后新建 style.css 文件
div.showing{
width:80%;
margin:20px auto;
border:1px solid grey;
padding:30px;
}
.even{
background-color: red;
}
.odd{
background-color: green;
}
步驟 3 : js 文件
在 webapp 目錄下新建 static/js 目錄,然后新建 thymeleaf.js 文件
function testFunction(){
alert("test Thymeleaf.js!");
}
步驟 4 : 修改 hello.html
通過 th:href="@{/static/css/style.css}" 和 th:src="@{/static/js/thymeleaf.js}" 引入 css 和 js 文件
<link rel="stylesheet" type="text/css" media="all" href="../../webapp/static/css/style.css" th:href="@{/static/css/style.css}"/>
<script type="text/javascript" src="../../webapp/static/js/thymeleaf.js" th:src="@{/static/js/thymeleaf.js}"></script>
注意幾點:
- 使用 @ 這種方式引入,在渲染后的 html 里會自動生成 上下文路徑,既如圖所示的 /thymeleaf 這個路徑
- 如果使用瀏覽器直接打開當前的 hello.html, 依然可以看到 css 和 js 效果,因為如下代碼起作用:
href="../../webapp/static/css/style.css"
src="../../webapp/static/js/thymeleaf.js"
所以這樣就非常方便前端開發和測試
- 在 header 標簽里有這么一段:
<script>
testFunction();
</script>
用以表示訪問 thymeleaf.js 里的 testFunction函數
完整 hello.html:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all" href="../../webapp/static/css/style.css" th:href="@{/static/css/style.css}"/>
<script type="text/javascript" src="../../webapp/static/js/thymeleaf.js" th:src="@{/static/js/thymeleaf.js}"></script>
<script>
testFunction();
</script>
</head>
<body>
<div class="showing">
<p th:text="${name}" >name</p>
<p th:text="'Hello! ' + ${name} + '!'" >hello world</p>
<p th:text="|Hello! ${name}!|" >hello world</p>
</div>
</body>
</html>
步驟 5 : 測試
運行 Application, 然后訪問如下地址進行測試:
如圖所示,可以看到 一個 js 的對話框,以及灰色的邊框效果。
這兩個效果是通過 @URL 外部引用 css 文件和 js 文件得到的。
更多關於 Springboot-thymeleaf-url 詳細內容,點擊學習: https://t.cn/A6Ag8wtM