準備
在html標籤加入如下語句
<html xmlns:th="http://www.thymeleaf.org">
js css 引用
https://blog.csdn.net/I_am_Yong_Ge/article/details/103016407
th:href="@{/layuiadmin/style/login.css}"
通過頁面鏈接跳轉
//java路由
@RequestMapping("/path1/path2/user")
public class PcUsersController {
@GetMapping("/login")
public String login() {
return "user/login";
}
//html中的路徑
<a th:href="@{/path1/path2/user/login}"
//實際訪問地址
http://localhost:8080/項目名/path1/path2/user/login
//路徑攜帶參數的2種方法
<a th:href="@{/path1/path2/user/test?a=1&b=2}"
//推薦
<a th:href="@{/path1/path2/user/test?(a=1,b=2)}"
html 獲取項目信息
<a th:href="${#httpServletRequest.getScheme()+'://'+#httpServletRequest.getServerName()+':'+#httpServletRequest.getServerPort()+#httpServletRequest.getContextPath()+'/icon/'+salecode } "/>
js中獲取項目名並跳轉
獲取項目名根路徑
<!-- th:inline表示在js中引用model的值 -->
<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/
var ctxPath1 = /*[[@{/}]]*/ '';
/*]]>*/
var ctxPath2 = [[${#httpServletRequest.getContextPath()}]];
console.log(ctxPath1)
console.log(ctxPath2)
//ctxPath1 = /項目名/
//ctxPath2 = /項目名
</script>
頁面跳轉
var rootPath = [[${#httpServletRequest.getContextPath()}]];
$.ajax({
url: rootPath + "/path1/path2/user/test",//這裏的/path1/path2/user/test是controller加接口的映射
type: "post",
contentType: "application/json",
datatype: "json",
data: JSON.stringify({
username: obj.field.username,
password: obj.field.password
}),
success: function (result) {
location.href = rootPath + '/path1/path2/user/test2'; //跳轉
}
});
Thymeleaf 獲取後臺的其他數據
後臺數據
@GetMapping("/test")
public String test(Model model) {
PagedResult pagedResult = new PagedResult();
pagedResult.setPage(1);
model.addAttribute("a","nihao");
model.addAttribute("pagedResult",pagedResult);
return "user/test";
}
html中獲取後臺數據
<a th:data="${a}" th:text="${a}">註冊帳號"${a}"</a>
<-- 註冊帳號"${a}" 裏面的變量無效,其他2個有效
th:text會替換 註冊帳號"${a}" -->
最後顯示效果
<a data="nihao">nihao</a>
js 中獲取後臺數據
<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/
var pages = /*[[${pagedResult.getPage()}]]*/ '';
/*]]>*/
console.log("pages = " + pages)
/*<![CDATA[*/
var a = /*[[${a}]]*/ '';
/*]]>*/
console.log("a = " + a)
<script>
打印結果
pages = 1
login:100 a = nihao
註釋
普通的註釋還是會被解析,導致報錯,解析失敗,需要採用下面的註釋
<!--/*-->
<div>
you can see me only before Thymeleaf processes me!
</div>
<!--*/-->