java Thymeleaf:将参数添加到当前 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27623405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:08:35  来源:igfitidea点击:

Thymeleaf: add parameter to current url

javaspring-mvcspring-bootthymeleafurl-parameters

提问by Andrea

I'm at

我在

http://example.com/some/page?p1=11

and I want to add a parameter to current url without having to redefine it:

我想向当前 url 添加一个参数而不必重新定义它:

http://example.com/some/page?p1=11&p2=32

with something like:

像这样:

<a th:href="@{?(p2=32)}">Click here</a>

but the above code return http://example.com/some/page?&p2=32(removes the p1parameter).

但是上面的代码返回http://example.com/some/page?&p2=32(删除了p1参数)。

How can I do it using Thymeleaf?

我怎样才能使用Thymeleaf做到这一点

回答by Václav Ku?el

You can use URI builder, directly from Thymeleaf.

您可以直接从 Thymeleaf 使用 URI 构建器。

<span th:with="urlBuilder=${T(org.springframework.web.servlet.support.ServletUriComponentsBuilder).fromCurrentRequest()}"
      th:text="${urlBuilder.replaceQueryParam('p2', '32').toUriString()}">
</span>

For URL http://example.com/some/page?p1=11prints out:

对于 URLhttp://example.com/some/page?p1=11打印:

http://example.com/some/page?p1=11&p2=32

Explained:

解释:

  • SpEL Toperatoris used for accessing ServletUriComponentsBuildertype.
  • An instance created by factory method fromCurrentRequestis saved to urlBuildervariable.
  • A param is added or replaced in the query string by replaceQueryParammethod, and then the URL is built.
  • SpELT运算符用于访问ServletUriComponentsBuilder类型。
  • 由工厂方法创建的实例fromCurrentRequest保存到urlBuilder变量中。
  • 通过replaceQueryParam方法在查询字符串中添加或替换参数,然后构建URL。

Pros:

优点:

  • Safe solution.
  • No trailing ?in case of empty query string.
  • No extra bean in Spring context.
  • 安全的解决方案。
  • ?在空查询字符串的情况下没有尾随。
  • Spring 上下文中没有额外的 bean。

Cons:

缺点:

  • It is quite verbose.
  • 它非常冗长。

! Be aware that solution above creates one instance of the builder. This means that the builder cannot be reused because it still modifies an original URL. For multiple URLs on a page you have to create multiple builders, like this:

!请注意,上述解决方案会创建一个构建器实例。这意味着构建器不能被重用,因为它仍然修改原始 URL。对于页面上的多个 URL,您必须创建多个构建器,如下所示:

<span th:with="urlBuilder=${T(org.springframework.web.servlet.support.ServletUriComponentsBuilder)}">
    <span th:text="${urlBuilder.fromCurrentRequest().replaceQueryParam('p2', 'whatever').toUriString()}"></span>
    <span th:text="${urlBuilder.fromCurrentRequest().replaceQueryParam('p3', 'whatever').toUriString()}"></span>
    <span th:text="${urlBuilder.fromCurrentRequest().replaceQueryParam('p4', 'whatever').toUriString()}"></span>
</span>

For http://example.com/some/pageprints:

对于http://example.com/some/page打印:

http://example.com/some/page?p2=whatever 
http://example.com/some/page?p3=whatever     
http://example.com/some/page?p4=whatever

回答by Raf

The easiest solution is concatenating "requestURI" and "queryString". Here is example:

最简单的解决方案是连接“requestURI”和“queryString”。这是示例:

<div th:with="currentUrl=(${#httpServletRequest.requestURI + '?' + #strings.defaultString(#httpServletRequest.queryString, '')})">
   <a th:href="@{${currentUrl}(myparam=test)}">click here</a>
</div>

Result for "http://localhost:8080/some-page?param1=1":

http://localhost:8080/some-page?param1=1”的结果:

 http://localhost:8080/some-page?param1=1&myparam=test

Result for "http://localhost:8080/some-page":

http://localhost:8080/some-page”的结果:

 http://localhost:8080/some-page?&myparam=test

Drawback:
Thymeleaf doesn't overwrite parameters - only adds parameters to URL. So if you user click once again to that URL, the result will be:

缺点:
Thymeleaf 不会覆盖参数 - 仅向 URL 添加参数。因此,如果您再次单击该 URL,结果将是:

http://localhost:8080/some-page?param1=1&myparam=test&myparam=test

References:
http://forum.thymeleaf.org/How-to-link-to-current-page-and-exchange-parameter-td4024870.html

参考资料:http:
//forum.thymeleaf.org/How-to-link-to-current-page-and-exchange-parameter-td4024870.html

EDIT:

编辑:

Here is some workaround, which removes parameter "myparam" from the URL:

这是一些解决方法,它从 URL 中删除参数“myparam”:

<div th:with="currentUrl=(${@currentUrlWithoutParam.apply('myparam')})">
    <a th:href="@{${currentUrl}(myparam=test)}">click here</a>
</div>

Next in Spring configuration:

接下来在 Spring 配置中:

@Bean
public Function<String, String> currentUrlWithoutParam() {
    return param ->   ServletUriComponentsBuilder.fromCurrentRequest().replaceQueryParam(param).toUriString();
}

For more "global" solution, I would try extending processor for attribute "th:href" or creating my own attribute. I'm not a thymeleaf expert, just facing similar problem.

对于更多“全局”解决方案,我会尝试为属性“th:href”扩展处理器或创建我自己的属性。我不是百里香专家,只是面临类似的问题。

回答by sndu

th:href="@{/your/link?parameter=__${appendParameter}__}"

回答by Hans Ke?ing

According to the docsyou can specify allparameters

根据文档,您可以指定所有参数

th:href="@{http://example.com/some/page(p1=11,p2=32)}"

You can use expressions to get values:

您可以使用表达式来获取值:

th:href="@{http://example.com/some/page(p1=11,p2=${someid})}"

回答by Lay Leangsros

This will work for you, even in Unicode:

这对你有用,即使在 Unicode 中:

 <ul class="pagination">
                <li th:if="${currentPage > 1}"><a th:href="'/search?key=' + ${param.key[0]} + '&amp;page=' +   ${currentPage-1}">Previous</a></li>

                      <li th:each="i : ${#numbers.sequence( 1, total+1)}" th:class="${i==currentPage}?active:''">
                            <a th:href="'/search?key=' + ${param.key[0]} + '&amp;page=' +   ${i}" th:inline="text">
                            [[${i}]] <span  class="sr-only">(current)</span>
                            </a>
                      </li>
                      <li><a th:if="${total + 1 > currentPage}" th:href="'/search?key=' + ${param.key[0]} + '&amp;page=' +   ${currentPage+1}">Next</a></li>
            </ul>