How to set a url that includes an ampersand with Thymeleaf?

I have something like:

Locale defaultLocale = Locale.getDefault(); final Context ctx = new Context(defaultLocale); String url = getHost() + "/page?someId=" + some.getId() + "&someParam=" + Boolean.TRUE; ctx.setVariable("url", url); final String htmlContent = templateEngine.process("theHtmlPage", ctx); 

But when I look at the received HTML for printing url , it shows & instead of & in the url.

Any suggestions?

I tried using backticks to avoid an ampersand in the Java code, but he just printed them too. I looked around, but did not find much that was relevant. Also tried &

Update: Well, this will not break the link, but Spring doesn't seem to resolve the "someParam" parameter as true without it.

Rendering Tag:

 <span th:utext="${url}"></span> 

Output:

 <span>http://localhost:8080/page?someId=1&amp;someParam=true</span> 
+6
source share
3 answers

Thymeleaf had a recent problem with screen shielding , which was fixed in 2.1.4.

+2
source

To avoid such problems, instead of the "&" character, you can use the UTF code for that character, for example, if you use UTF-8 '\ u0026'.

+2
source

Better use a dedicated thymeleaf link url simulator .

If you want to build and set a URL with two parameters and set it to the href attribute, you can do it 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 ask:

 page?param1=val1&param2=val2 

=== EDIT ===

To answer downvote of dopatraman, I just checked (again) my answer and it works well.

In my answer, the ampersand used as a parameter delimiter is automatically added by the thimeleaf. And this added ampersand is a thimeleaf encoded html object that will be stored in html .

If you have another ampersand inside param1 or param2, this ampersand should be an html object encoded inside the thimeleaf template . But it will be displayed in percent encoded in the generated html .

Example (tested with thimeleaf 2.1.5.RELEASE):

param1 is abc and param2 is 12&3

Inside the thimeleaf template, all ampersands should be encoded as an html object, 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 object, and the ampersand in the param2 value is encoded with a percent thimeleaf:

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

When you click on the link, the browser will decode the encoding of the html entity, but not the percent encoding, and the URL in the address bar will be:

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

Testing with wirehark, we get on HTTP request:

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

Source: https://habr.com/ru/post/984721/


All Articles