html中如何引入css或者js
比如我們需要引入jquey和bootstrap,資源文件結(jié)構(gòu)

image.png
頁(yè)面中使用@默認(rèn)從static下面尋找資源文件.
html,其中src路徑在我們不啟動(dòng)服務(wù)的時(shí)候,直接通過(guò)src可以訪問(wèn)到資源文件,當(dāng)啟動(dòng)服務(wù)的時(shí)候模板引擎將th:ref的屬性替換掉默認(rèn)的ref屬性
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>測(cè)試</title>
<link rel="stylesheet" type="text/css" media="all"
href="../../static/plugins/bootstrap/css/bootstrap.css" th:href="@{/plugins/bootstrap/css/bootstrap.css}" />
</head>
<body>
<table class="table">
<tr>
<td class="active">測(cè)試1</td>
<td class="success">測(cè)試2</td>
<td class="warning">測(cè)試3</td>
<td class="danger">測(cè)試4</td>
<td class="info">測(cè)試5</td>
</tr>
</table>
</body>
<script type="application/javascript" th:src="@{/plugins/jquery/jquery-3.3.1.min.js}" src="../../static/plugins/jquery/jquery-3.3.1.min.js" ></script>
<script type="application/javascript" th:src="@{/plugins/bootstrap/js/bootstrap.js}" src="../../static/plugins/bootstrap/js/bootstrap.js"></script>
<script type="application/javascript">
$(function(){
console.log($);
})
</script>
</html>
獲取contentpath
如果有contentpath,需要加上項(xiàng)目名字的時(shí)候,應(yīng)該怎么獲取
<span th:text="${#httpServletRequest.getScheme() + '://' + #httpServletRequest.getServerName() + ':' + #request.getServerPort() + #request.getContextPath() + '/'} "
id="contextPath"></span>
thymeleaf中支持多種內(nèi)置對(duì)象,比如
- ctx:上下?對(duì)象。
- vars:上下?變量。
- locale:上下?區(qū)域設(shè)置。
- request :(僅在Web Contexts中)HttpServletRequest對(duì)象
- response:(僅在Web上下?中)HttpServletResponse對(duì)象。
- session :(僅在Web上下?中)HttpSession對(duì)象。
-
servletContexte :(僅在Web上下?中)ServletContext對(duì)象
...
我們可以從這些內(nèi)置對(duì)象中獲取到比如session中的當(dāng)前用戶對(duì)象;
image.png
歡迎您<span th:text="${#session.getAttribute('loginUser')}"></span>
頁(yè)面跳轉(zhuǎn)路徑需要這樣寫
<a href="" th:href="${#httpServletRequest.getContextPath()+'/test'}">跳轉(zhuǎn)</a>
引入公共代碼片段
比如我們希望引入一個(gè)頁(yè)面的頭部或者尾部的公共部分
首先在需要引入的html片段定義一個(gè)名稱
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>common</title>
</head>
<body>
<div th:fragment="nav" class="navbar navbar-default navbar-static-top">
公共部分的html片段,名稱為nav
</div>
頁(yè)面中去引入此片段,使用th:insert 或者th:replace均可,insert唯一的區(qū)別是插入宿主片段中,而replace是替換掉宿主的片段.
歡迎您<span th:text="${#session.getAttribute('loginUser')}"></span>
<br/>
<div th:insert="~{common/common :: nav}"></div>
<table class="table">
<tr>
<td class="active">測(cè)試1</td>
<td class="success">測(cè)試2</td>
<td class="warning">測(cè)試3</td>
<td class="danger">測(cè)試4</td>
<td class="info">測(cè)試5</td>
</tr>
</table>

image.png
用法
- ~{templatename :: selector} 前面是模板名稱,后面是選擇器
- ~{:: selector} 不指定模板從當(dāng)前頁(yè)面查找
片段引入還有其他的寫法,可以不定義片段直接使用選擇器的方式
比如在common中同樣有這樣的一個(gè)代碼片段,但是沒(méi)有定義卻有id
<div id="footer" >
© 2018 今天天氣還不錯(cuò)
</div>
那么可以這樣引用
//代表從common/common 的頁(yè)面中,尋找Id 為footer的字段
<div th:replace="~{common/common :: #footer}"></div>
