Home > Software engineering >  Thymeleaf generates URL with no query parameters, but '?' appears
Thymeleaf generates URL with no query parameters, but '?' appears

Time:04-11

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 >Details</button>
            </form>
        </td>

        <td>
            <form th:object="${dept}" th:action="@{/departments/{id}/edit(id=${dept.getId()})}">
                <button >Edit</button>
            </form>
        </td>
        <td>
            <form th:object="${dept}" th:action="@{/departments/{id}(id=${dept.getId()})}" th:method="delete">
                <button >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?

CodePudding user response:

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

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

CodePudding user response:

Try

<form th:object="${dept}" th:action="@{/departments/edit/{id}(id=${dept.getId()})}">
  • Related