前言

  • thymeleaf 3.0

获取绝对路径

使用Thymeleaf模板引擎想要拼出绝对路径

<a th:href="${#request.getScheme() + '://' + #request.getServerName() + ':' + #request.getServerPort() + @{/login}} ">点我啊!</a>

等效的写法:

<a th:href="${#httpServletRequest.getScheme() + '://' + #httpServletRequest.getServerName() + ':' + #httpServletRequest.getServerPort() + @{/login}} ">点我啊!</a>

解释下:

Inside a web environment there is also direct access to the following objects (note these are objects, not maps/namespaces):
#request : direct access to the javax.servlet.http.HttpServletRequest object associated with the current request.

按照官方文档的说法,内置变量 #request 等同于 javax.servlet.http.HttpServletRequest
因此,可以按照 javax.servlet.http.HttpServletRequest 拼接URL的方式,拼接绝对路径。

javax.servlet.http.HttpServletRequest 的方法说明

  • getScheme() 获取协议
  • getServerName() 获取服务器名
  • getServerPort() 服务器端口
  • getContextPath() APP根路径

勘误

之前给出的写法有些问题,已修正。

下面是之前给出的错误的写法:

<a th:href="${#httpServletRequest.getScheme() + '://' + #httpServletRequest.getServerName() + ':' + #request.getServerPort()  + #request.getContextPath() + @{/login}} ">点我啊!</a>

参考

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-a-expression-basic-objects

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐