Getting a URL Attribute Value in Thymeleaf – 在Thymeleaf中获得一个URL属性值

最后修改: 2022年 9月 30日

1. Overview


In this short tutorial, we’ll shed light on how to get URL attributes in the Thymeleaf views.


2. How to Get URL Parameter Attributes


Accessing URL attributes, or what we call request parameters, can be easily done in Thymleaf views using one of two special Thymleaf objects. The first way is to use the param object, and the second way is to use the #request object.


For demonstration purposes, let’s consider a URL that holds one parameter, query:


2.1. Using the param Object


First, let’s see how to use the param object to access the URL attribute “query”:

首先,让我们看看如何使用param对象来访问URL属性 “query”。

<div th:if="${param.query != null}">
    <p th:text="${param.query }"></p>

In the above example, if the parameter “query” isn’t null, the value of “query” will be shown. Also, we should note that URL attributes can be multivalued. Let’s see an example URL with a multivalued attribute:

在上面的例子中,如果参数 “query “不是空的,”query “的值将被显示。另外,我们应该注意,URL属性可以是多值的。让我们看看一个带有多值属性的URL例子。

In this case, we can access the values separately using brackets syntax:


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

2.2. Using the request Object


Next, let’s see the second way to access URL attributes. We can use the special #request object that gives you direct access to the javax.servlet.http.HttpServletRequest object, which breaks a request down into parsed elements such as query attributes and headers.


Let’s see how to use the #request object in a Thymleaf view:


<div th:if="${#request.getParameter('query') != null}">
    <p th:text="${#request.getParameter('query')}" th:unless="${#request.getParameter('query') == null}"></p>

In the above example, we used the special function getParameter(‘query’) offered by the #request object. This method returns the value of a request parameter as a String, or null if the parameter does not exist.


3. Conclusion


In this quick article, we explained how to get URL attributes in the Thymeleaf views using param and #request objects. As always, the code snippets are available over on GitHub.