Arya
Arya

Reputation: 8985

Generating correct url for page link

I have implemented pagation in my Spring boot application. There are no problems in the logic of it, however I am running into a weird issue with Thymeleaf.

Right now if I go to the following url

http://localhost:8080/Phoenix-listings

and if I hover my mouse over the link to page 2 is

http://localhost:8080/2

which is the wrong link, but if I manually go to the following url

http://localhost:8080/Phoenix-listings/1

then if I hover my mouse over page 2, then the link is

http://localhost:8080/Phoenix-listings/2

which is how it should be.

How can I make the correct link get generated even if I am in http://localhost:8080/Phoenix-listings?

Below is the section related to my pagation in Thymeleaf

<div class="row">
    <div th:if="${ads.totalPages != 1}"
        class="form-group col-md-11 pagination-centered">
        <ul class="pagination">
            <li th:class="${ads.number == 0} ? disabled"><a
                class="pageLink" th:href="1">&laquo;</a></li>
            <li th:class="${ads.number == 0} ? disabled"><a
                class="pageLink" th:href="${ads.number}">&larr;</a></li>
            <li
                th:class="${ads.number == (page - 1)} ? 'active pointer-disabled'"
                th:each="page : ${#numbers.sequence(pager.startPage, pager.endPage)}">
                <a class="pageLink" th:href="${page}" th:text="${page}"></a>
            </li>
            <li th:class="${ads.number + 1 == ads.totalPages} ? disabled">
                <a class="pageLink" th:href="${ads.number + 2}">&rarr;</a>
            </li>
            <li th:class="${ads.number + 1 == ads.totalPages} ? disabled">
                <a class="pageLink" th:href="${ads.totalPages}">&raquo;</a>
            </li>
        </ul>
    </div>
</div>

Upvotes: 0

Views: 87

Answers (1)

Metroids
Metroids

Reputation: 20487

In this case, you should be using thymeleaf's built in url syntax. It would look like this:

th:href="@{/{page}(page=${page})}"

Creating a link with @{/} means that thymeleaf automatically adds the context (Phoenix-listings in your case.) {page} is a placeholder. (page=${page}) replaces the placeholder with the variable.

You can also use string concatenation, but I wouldn't recommend it in most cases (because using the standard syntax means thymeleaf can correctly encode urls).

th:href="@{${'/' + page}}"

Upvotes: 1

Related Questions