【thymeleaf】 Link (URL) expressions: 使用 Link 表达式创建 URL
前言
- thymeleaf version: 3.0.11.RELEASE
- spring boot 2.0.0.RELEASE
概述
Link 表達式在創(chuàng)建URL時向URL中添加有用的上下文和會話信息(通常稱為URL重寫的過程)。
舉個例子進行一下說明。假如有個項目,將之發(fā)布為/myapp(/myapp就是 application context)。
來個 Link 表達式:
在代碼執(zhí)行后,將獲得下面這樣的輸出:
<a href="/myapp/order/list">...</a>就這樣/myapp就被加入到了url中。
將 Application Context 加入到URL中
前面的例子就是了。
將 Session ID(jsessionid)加入到URL中
來個 Link 表達式:
<a th:href="@{/order/list}">...</a>在代碼執(zhí)行后,將獲得下面這樣的輸出:
<a href="/myapp/order/list;jsessionid=23fa31abd41ea093">...</a>就這樣jsessionid就被加入到了url中。
那么問題來了,jsessionid在什么情況下被加入,什么情況下不被加入呢?可以簡單理解為是thymeleaf自己判斷的。
jsessionid被加入的條件:
if we need to keep sessions and cookies are not enabled (or the server doesn’t know yet)
原文在這里
將 @RequestParam 加入到URL中
來個 Link 表達式:
<a th:href="@{/order/details(id=${orderId},type=${orderType})}">...</a>注:${orderId}、${orderType}
Thymeleaf will always call the HttpServletResponse.encodeUrl(…) mechanism before displaying the URL
在代碼執(zhí)行后,將獲得下面這樣的輸出:
<!-- Note ampersands (&) should be HTML-escaped in tag attributes... --> <a href="/myapp/order/details?id=23&type=online">...</a>將 @PathVariable 加入到URL中
來個 Link 表達式:
<a th:href="@{/order/{orderId}/details(orderId=${o.id})}">...</a>注:orderId出現(xiàn)了2次哦。
在代碼執(zhí)行后,將獲得下面這樣的輸出:
<a href="/myapp/order/3/details">...</a>將 @RequestParam 和 @PathVariable 一起加入到URL中
來個 Link 表達式:
<a th:href="@{/order/{orderId}/details(orderId=${o.id},userid=${u.id})}">...</a>注:orderId出現(xiàn)了2次哦。
在代碼執(zhí)行后,將獲得下面這樣的輸出:
<a href="/myapp/order/3/details?userid=2">...</a>計算相對地址
綜上所述,當以/開頭時,可以理解為項目中的絕對地址。
除了項目中的絕對地址外,還可以寫相對地址。按照下面這樣做就行了。
來個 Link 表達式:
在代碼執(zhí)行后,將獲得下面這樣的輸出:
<a href="../contents/main">...</a>注:未將 application context 添加到url中
---------------------------我是分割線---------------------------
當處在/myapp/user/details位置的時候,想生成指向/myapp/contents/main的URL怎么辦?
Link 表達式:
計算相對于 Server 的絕對路徑
來個 Link 表達式:
<a th:href="@{~/contents/main}">...</a>在代碼執(zhí)行后,將獲得下面這樣的輸出:
<a href="/contents/main">...</a>注:未將 application context 添加到url中
URL中帶上域名
Link 表達式:
<a th:href="@{//www.mycompany.com/main}">...</a>URL中帶上協(xié)議
Link 表達式:
<a th:href="@{http://www.mycompany.com/main}">...</a>將URL拼接到字符串中
<a th:οnclick="'javascript:brand_edit(\'' + ${url} + '\')'" th:with="url=@{/order/details/{orderId}(orderId=${o.id})}">...</a>在代碼執(zhí)行后,將獲得下面這樣的輸出:
<a href="javascript:brand_edit('/myapp/order/details/80914336158')">...</a> 與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的【thymeleaf】 Link (URL) expressions: 使用 Link 表达式创建 URL的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 移动2G上网速度加快的方法
- 下一篇: 【springboot】上传文件到Fas