我想显示一个在运行时使用参数生成的绝对URL。不创建页面的href,而是使用th:text
显示URL。用Tymeleaf做任何简单的方法(不必连接#request对象的URL片段而不使用某些MVC实用程序类)?
尝试1
<p th:text="@{/myServlet(myParam=${dynamicParameter})}" />
- 仅显示部分URL,不包括协议,端口和主机名。我得到了/myServlet?myParam=123
。与th:href
相同的行为,如果您检查<a>
,您将看到相同的href - 在这种情况下,浏览器会通过推断协议,端口等来帮助
尝试2
th:text="@{__${#httpServletRequest.requestURI}__}"
- 生成当前页面的相对URI,该URI不包含协议等等
尝试3
th:text="@{__${#httpServletRequest.requestURL}__}"
- 这次生成包含协议,主机和servlet上下文的当前页面的绝对URL。现在的问题是,当我从其他页面显示此文本时,我的网址为...myApp/myOtherServlet
,因此我需要编辑此字符串以使用我想要的URI替换myOtherServlet
。
非Tymeleaf尝试1
@Service("urlUtils")
public class UrlUtilsServiceImpl implements UrlUtilsService {
@Override
public String getAbsoluteUrlTo(final String aPath, final String param, final String value){
return ServletUriComponentsBuilder
.fromCurrentContextPath()
.path(aPath)
.queryParam(param, value)
.build().toString();
}
}
page.html中:
th:text="${@urlUtils.getAbsoluteUrlTo('/myServlet', 'myParam', ${dynamicParameter})}"
问题是主机名在到达我的服务器之前可以别名(请参阅this)。 Thymeleaf + JS Sollution
使用一些java脚本加上thymeleaf
<p id="myUrl" th:text="@{/myServlet(myParam=${dynamicParameter})}" />
<script type="text/javascript">
$(document).ready(function () {
var myUrl= $("#myUrl");
myUrl.text(window.location.origin + myUrl.text());
});
</script>
答案 0 :(得分:0)
您可以动态连接servlet请求:
th:text="${#httpServletRequest.scheme}+'://'+${#httpServletRequest.serverName}+':'+${#httpServletRequest.serverPort}+@{/myServlet(myParam=${dynamicParameter})}"
或者对于JavaScript:
<script type="text/javascript">
GLOBAL.serverURI = '[[${#httpServletRequest.scheme}+'://'+${#httpServletRequest.serverName}+':'+${#httpServletRequest.serverPort}+@{/myServlet(myParam=${dynamicParameter})}]]';
</script>