Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

java - Thymeleaf: add parameter to current url

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:

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 p1 parameter).

How can I do it using Thymeleaf?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use URI builder, directly from Thymeleaf.

<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=11 prints out:

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

Explained:

  • SpEL T operator is used for accessing ServletUriComponentsBuilder type.
  • An instance created by factory method fromCurrentRequest is saved to urlBuilder variable.
  • A param is added or replaced in the query string by replaceQueryParam method, and then the URL is built.

Pros:

  • Safe solution.
  • No trailing ? in case of empty query string.
  • No extra bean in Spring context.

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:

<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/page prints:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...