前言
- thymeleaf version: 3.0.11.RELEASE
- spring boot 2.0.0.RELEASE
概述
Link 表达式在创建URL时向URL中添加有用的上下文和会话信息(通常称为URL重写的过程)。
举个例子进行一下说明。假如有个项目,将之发布为/myapp
(/myapp
就是 application context)。
来个 Link 表达式:
<a th:href="@{/order/list}">...</a>
在代码执行后,将获得下面这样的输出:
<a href="/myapp/order/list">...</a>
就这样/myapp
就被加入到了url中。
将 Application Context 加入到URL中
前面的例子就是了。
将 Session ID(jsessionid)加入到URL中
来个 Link 表达式:
<a th:href="@{/order/list}">...</a>
在代码执行后,将获得下面这样的输出:
<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
在代码执行后,将获得下面这样的输出:
<!-- 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出现了2次哦。
在代码执行后,将获得下面这样的输出:
<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出现了2次哦。
在代码执行后,将获得下面这样的输出:
<a href="/myapp/order/3/details?userid=2">...</a>
计算相对地址
综上所述,当以/
开头时,可以理解为项目中的绝对地址。
除了项目中的绝对地址外,还可以写相对地址。按照下面这样做就行了。
来个 Link 表达式:
<a th:href="@{../contents/main}">...</a>
在代码执行后,将获得下面这样的输出:
<a href="../contents/main">...</a>
注:未将 application context 添加到url中
---------------------------我是分割线---------------------------
当处在/myapp/user/details
位置的时候,想生成指向/myapp/contents/main
的URL怎么办?
Link 表达式:
<a th:href="@{../../contents/main}">...</a>
计算相对于 Server 的绝对路径
来个 Link 表达式:
<a th:href="@{~/contents/main}">...</a>
在代码执行后,将获得下面这样的输出:
<a href="/contents/main">...</a>
注:未将 application context 添加到url中
URL中带上域名
Link 表达式:
<a th:href="@{//www.mycompany.com/main}">...</a>
URL中带上协议
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>
在代码执行后,将获得下面这样的输出:
<a href="javascript:brand_edit('/myapp/order/details/80914336158')">...</a>