Search code examples
spring-bootspring-mvcthymeleafspring-thymeleaf

Thymeleaf generates URL with no query parameters, but '?' appears


I'm working on a simple Spring Boot MVC application using Thymeleaf.

Part of the thymeleaf code:

         <tr th:each="dept: ${departments}">

        <td th:text="${dept.getId()}"></td>
        <td th:text="${dept.getName()}"></td>
        <td>
            <form th:object="${dept}" th:action="@{'/departments/' + ${dept.getId()}}">
                <button class="btn btn-secondary">Details</button>
            </form>
        </td>

        <td>
            <form th:object="${dept}" th:action="@{/departments/{id}/edit(id=${dept.getId()})}">
                <button class="btn btn-secondary">Edit</button>
            </form>
        </td>
        <td>
            <form th:object="${dept}" th:action="@{/departments/{id}(id=${dept.getId()})}" th:method="delete">
                <button class="btn btn-secondary">Delete</button>
            </form>
        </td>
    </tr>

The UI interface looks like this:

enter image description here

When clicking on the Edit button (same goes for the Details one), it loads correctly, but the URL generates the ? character for other query parameters, but there are actually none (for example http://localhost:8089/departments/3/edit?).

enter image description here

The controller code is:

@GetMapping("/{id}/edit")
public String editDepartment(@PathVariable("id") String departmentId, Model model) {
    var department = departmentService.getDepartmentById(Long.valueOf(departmentId));
    model.addAttribute("department", department);
    return "edit-department"; // returns view
}

My problem is with the ? character that is being displayed. I don't want it to appear as there are no query parameters. Any help?


Solution

  • It's adding a question ? because you are submitting an empty form. Why not just use a link styled as a button?

    <a class="btn btn-secondary" th:href="@{/departments/{id}/edit(id=${dept.id})}" role="button">Edit</a>