有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在thymeleaf中构建绝对URL?

我想用一个参数显示运行时生成的绝对url。不创建页面的href,而是使用th:text显示URL。使用TymeLab有没有简单的方法来实现这一点(不必连接来自#请求对象的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}__}"-这次生成当前页面的绝对URL,其中包含协议、主机和servlet上下文。现在的问题是,当我从另一个页面显示这个文本时,我的URL是...myApp/myOtherServlet,所以我需要编辑这个字符串,用我想要的URI替换myOtherServlet

非季莫莱夫尝试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();
    }
}

佩奇。html:

th:text="${@urlUtils.getAbsoluteUrlTo('/myServlet', 'myParam', ${dynamicParameter})}"

问题是主机名在到达我的服务器之前可能会被化名(请参见this)。 Thymeleaf+JS解决方案

使用一些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>

共 (1) 个答案

  1. # 1 楼答案

    您可以动态连接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>