5

I have an existing URL with get parameters. On a button click, I want to change one specific URL parameter, but retain the others. Is that possible?

Thymeleaf template:

<a th:href="@{/order/details(id=3)}">

Results in:

<a href="/order/details?id=3">

What if I want to

  • preserve other parameters in the URL
  • override the id parameter?

Desired result of the thymeleaf template above:

localhost:8080/order/details?name=test&id=3

Preferably without javascript.

membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • What do you mean by "on a button click"? Will send request to server? or just directly want to change the params in links? – Zico Aug 10 '17 at 10:56
  • Both. I have a
    `, thus on click the url changes (automatically) and calls the backend service url.
    – membersound Aug 10 '17 at 11:05
  • So, that should be done using JS. Not by thymeleaf – Zico Aug 10 '17 at 11:25
  • Please look at this [answer](https://stackoverflow.com/a/68212965/3271406). It should fit your needs. – lu_ko Jul 01 '21 at 15:28

2 Answers2

5

Even though it's an older question, I hope this could still help:

<a th:href="@{${urlBuilder.replaceQueryParam('id', 3).build().toUriString()}}" th:with="urlBuilder=${T(org.springframework.web.servlet.support.ServletUriComponentsBuilder).fromCurrentRequest()}">

This builds a complete URI string, including the HTTP(S) part. So if you use (for example) a load balancer for your web applications and it doesn't forward https requests directly, you will get a wrong URI string. In this case, you have to do it like Zico wrote: Set the baseUrl in the controller and bind it to the template. You could also get the query string from the current request: request.getQueryString() or use the ServletUriComponentsBuilder class in your controller.


Edit

You can apply .scheme('https') to urlBuilder (@{${urlBuilder.replaceQueryParam('id', 3).scheme('https').build().toUriString()}}). E.g. you can create a method in your controller which gets the X-Forwarded-Proto from your load balancer.

Check example #27 from here: https://www.programcreek.com/java-api-examples/?api=org.springframework.web.servlet.support.ServletUriComponentsBuilder

toco
  • 61
  • 1
  • 4
2

Set the baseURL from controller then bind baseURL to template

In Controller:

@RequestMapping(value = "/test", method = RequestMethod.GET)
  public String home(ModelMap model, HttpServletRequest req) {
  String baseUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath();
  ....
  model.addAttribute("baseUrl", baseUrl);
  model.addAttribute("name", name);
  .....

In Template:

<a th:href="@{__${baseUrl}__/order/details(name=${name},id=3)}">
Zico
  • 2,349
  • 2
  • 22
  • 25