Reputation: 470
I am sending a string pathvariable from a thymeleaf href template to a Spring-boot controller but if a URL is contained in this string, its slash characters "//" get interpreted as a part of the href URL. Is there a way how to get these symbols automatically escaped?
thymeleaf
<a th:href="@{/displayComments/{comments}(comments=${excerpt.comments})}">Comments</a>
where
comments=${excerpt.comments} = 'https://www.youtube.com/watch%3Fv=j1wgaFJ0750'
and the URL is reported with There was an unexpected error (type=Not Found, status=404)
http://localhost:8080/displayComments/https://www.youtube.com/watch%3Fv=j1wgaFJ0750
Upvotes: 1
Views: 1464
Reputation: 21918
Thymeleaf will automatically URL encode query parameters (content following a ?
).
But here you want to URL encode a URL path segment - so you need to explicitly handle that:
th:href="@{/displayComments/{comments}(comments=${#uris.escapePathSegment(excerpt.comments, 'UTF-8')})}"
I recommend using the version of the function which takes an encoding parameter, so you can explicitly use UTF-8
and avoid being tripped up by unexpected default encodings.
Upvotes: 2