准备
在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>
<!--*/-->