1. Introduction
Thymeleaf is a template engine created for Java-based applications. It comes with many great features and some awesome utility methods, useful in the development process. In this article, we will showcase the URI/URL
utility methods used for performing operations like escaping/unescaping strings inside Thymeleaf standard expressions. The implementation of URI/URL utility methods can be found in the official Thymeleaf GitHub Repository.
If you want to learn how to construct URLs in Thymeleaf follow that link.
2. Available utility methods for URI/URL
Method | Purpose | Description |
---|---|---|
${#uris.escapePath(uri)} ${#uris.escapePath(uri, encoding)} ${#uris.unescapePath(uri)} ${#uris.unescapePath(uri, encoding)} |
Escape/Unescape as a URI/URL path | Allowed characters in URI path are: A-Z a-z 0-9 , - . _ ~ , ! $ & ' ( ) * + , ; = , @ , / . Those chars will not be escaped. All other chars converted to the sequence of bytes that represents them in the specified encoding and then representing each byte in the hexadecimal representation of that byte.
|
${#uris.escapePathSegment(uri)} ${#uris.escapePathSegment(uri, encoding)} ${#uris.unescapePathSegment(uri)} ${#uris.unescapePathSegment(uri, encoding)} |
Escape/Unescape as a URI/URL path segment (between '/' symbols) | Escapes the given string for use as a URL path segment |
${#uris.escapeFragmentId(uri)} ${#uris.escapeFragmentId(uri, encoding)} ${#uris.unescapeFragmentId(uri)} ${#uris.unescapeFragmentId(uri, encoding)} |
Escape/Unescape as a Fragment Identifier (#frag) | Escapes the given string for use as a URL path segment |
${#uris.escapeQueryParam(uri)} ${#uris.escapeQueryParam(uri, encoding)} ${#uris.unescapeQueryParam(uri)} ${#uris.unescapeQueryParam(uri, encoding)} |
Escape/Unescape as a Query Parameter (?var=value) | Escapes the given string for use as a URL query param |
3. Usage examples
In the following example we showed how to use uri
escape methods.
This will produce the following output:
4. Conclusion
In this article, we presented Thymeleaf utility methods for URI/URL
created to escape/unescape special characters that couldn't be used in URLs. You can use it to build safe links to articles or other resources.
Code used in this article can be found at our GitHub repository.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}