4

Is there any special tool in Thymeleaf to construct URLs by adding/removing/replacing parameters? For example, I need to make a request to the same page but adding one additional parameter "p=1" into the request. So that:

'/foo?a=b' becomes '/foo?a=b&p=1' // addition
'/foo?p=0' becomes '/foo?p=1'     // replacing

@{} doesn't seem to be helpful here. I would imagine something like the following to exist: @{#currentUri(*, p=1, !q)}, where '*' is for all existing params, 'p=1' means add/replace and '!' means excluding.

Does Thymeleaf have anything like that or any other syntax for flexible URL construction?

Alex Vayda
  • 6,154
  • 5
  • 34
  • 50
  • Please look at this [answer](https://stackoverflow.com/a/68212965/3271406). It should fit your needs. – lu_ko Jul 01 '21 at 15:29

2 Answers2

1

I know its a while ago when you asked this question, anyhow.

It seems that your are looking for the httpServeltRequest.requestURI

<a th:href="@{${'~' + #httpServletRequest.requestURI}(lang=${language})}" th:text="#{${'Language.' + lang}}"><span>Switch to English</span></a>

And with the #httpServletRequest.QueryString you can get all the parameters given in the current url. Unfortunatly I'm not shure if you can exclude any parameters.

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

Michiel Bijlsma
  • 583
  • 5
  • 10
  • `queryString` is just a string and it would be tricky to reconstruct the URL with modifications as a 1-line expression. It would require to brake the query string into keys and values and then reconstruct URL param by param. – Alex Vayda Jul 16 '14 at 13:34
0

It seems like Thymeleaf does not provide any such utility.

But, since it leverages Spring EL it is fairly easy to write a helper class with a set of utility methods and make it available for the expressions to call those methods. Syntactically it can look very close to the imaginary example from the question: @{#currentUri("*", "p=1", "!q")}

Alex Vayda
  • 6,154
  • 5
  • 34
  • 50