Can I make HTTP POST request from Thymeleaf table in Spring Boot application

妖精的绣舞 提交于 2019-12-03 16:26:08
Rayweb_on

you are using Links and I don't think that is possible, you would need to use a form where you can specify the method POST to be used.

In the example below im using a <button> instead of a <a> element, but it will work, the only thing you need to do is to style your button with CSS to look like your links

<form method="POST" th:action="@{/edit(personId=${person.personId})}">
    <button type="submit" name="submit" value="value" class="link-button">This is a link that sends a POST request</button>
</form> 

now in your code should look like this

<tr th:each="person : ${persons}">                
    <td th:text="${person.personId}"></td>
    <td th:text="${person.name}"></td>
    <td th:text="${person.address}"></td>
    <td th:text="${person.telephone}"></td>
    <td th:text="${person.email}"></td>
    <td>
        <form method="POST" th:action="@{/edit(personId=${person.personId})}">
            <button type="submit" name="submit" value="value" class="link-button">EDIT</button>
        </form> | 
        <form method="POST" th:action="@{/delete(personId=${person.personId})}">
            <button type="submit" name="submit" value="value" class="link-button">DELETE</button>
        </form>
    </td>
</tr>

EDIT

As you just shared you Java code, in the controller you are expecting the personId not as a PathVariable, but as a RequestParam, in that case your form should have that value...

edit your form and add the person id as follows.

<form method="POST" th:action="@{/edit}">
    <input type="hidden" name="personid" id="personId" th:value="${person.personId}" />
    <button type="submit" name="submit" value="value" class="link-button">This is a link that sends a POST request</button>
</form> 

Notice also I changed the action of the form to be just /edit, as its what your controller looks like

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!