How to get URL query parameter value in Thymeleaf?

November 01, 2020 No comments Thymeleaf query parameter URL QA

1. Problem

In this short Q&A article, we are going to show how to get URL request parameters in Thymeleaf template view.

2. Solution

Luckily, request parameters can be easily accessed in Thymeleaf views using built-in tools.

For request parameters like in the following URL:

In order to access query parameter we could use the param object:

<div th:if="${(param.query != null) and (param.query[0] == 'Thymeleaf')}">
    Thymeleaf is awesome

Another way to access URL parameters is by using the special #request object that gives you direct access to the javax.servlet.http.HttpServletRequest class:

<div th:if="${#request.getParameter('query') != null and #request.getParameter('query') == 'Thymeleaf'}">
    Thymeleaf is awesome

Note that parameters could be multivalued like in the following example:

In this case we need to use an index of the array:

<p th:text="${param.query[0] + ' ' + param.query[1]}" th:unless="${param.query == null}">Test</p>

To iterate over array we could use th:each attribute.

{{ message }}

{{ 'Comments are closed.' | trans }}