How do I set a URL that includes an ampersand with Thymeleaf?

To avoid this kind of problems instead of '&' symbol you can use UTF code for that symbol, e.g in case of UTF-8 use '\u0026'.


Thymeleaf had a recent issue with encoding escapes, which has been fixed in 2.1.4.


It's better to use the dedicated thymeleaf link url syntax.

If you want to construct and url with two parameters and set it to an href attribute you can do like this:

<a th:href="@{page(param1 = ${param1}, param2 = ${param2})}">link</a>

The generated html will be:

<a href="page?param1=val1&amp;param2=val2">link</a>

and the browser will request:

page?param1=val1&param2=val2

=== EDIT ===

To answer the downvote of dopatraman, I've just tested (again) my answer and it works well.

In my answer, the ampersand used as a parameters separator is automatically added by thymeleaf. And this added ampersand is html entity encoded, by thymeleaf, to be stored in the html.

If you have another ampersand inside param1 or param2, this ampersand should be html entity encoded inside the thymeleaf template. But it will appear percent encoded in the generated html.

Example (tested with thymeleaf 2.1.5.RELEASE):

param1 has value abc and param2 has value 12&3

Inside the thymeleaf template all ampersand must be encoded as html entity and we have:

<a th:href="@{page(param1 = ${'abc'}, param2 =${'12&amp;3'})}">link</a>

In the generated html, the ampersand used as a parameter separator is encoded as an html entity and the ampersand in the param2 value is percent-encoded by thymeleaf:

<a href="page?param1=abc&amp;param2=12%263">link</a>

When you click on the link, the browser will decode the html entity encoding but not the percent-encoding, and the url in the adress bar will be:

<a href="page?param1=abc&amp;param2=12%263">link</a>

Checking with wireshark, we obtain from the HTTP request:

GET /page?param1=abc&param2=12%263