Thymeleaf - Button click to call http delete method

后端 未结 2 1597
我寻月下人不归
我寻月下人不归 2021-01-04 18:44

I would like to call the url via http delete method. I tried th:onclick and th:action but not working.

html code:

相关标签:
2条回答
  • 2021-01-04 18:59

    I think you will need a form for your transaction. And also this hidden input field.

    <form action="#" th:action="@{'/delete/{id}'(id=${foo.id})}" th:method="delete" >
      <input type="hidden" name="_method" value="delete" />
      <button type="submit" id="submitButton"> </button>
    </form>
    
    0 讨论(0)
  • 2021-01-04 19:04

    The th:method="delete" creates the hidden input field automatically for you. If you add it manually as well you will have it twice. Check the source code.

    I still got the POST Error message after the recommendations here. I found out Spring ignores those hidden fields by default. The solution is to activate it in your application.properties file:

    spring.mvc.hiddenmethod.filter.enabled=true
    

    My working code in my application looks like this:

    Form:

    <form action="#" th:action="@{'/books/delete/{id}'(id=${book.id})}" th:method="delete" >
        <button type="submit" class="btn">
            Delete
        </button>
    </form>
    

    Controller:

    @RequestMapping(value="/books/delete/{id}", method = RequestMethod.DELETE)
    public String deleteBook(@PathVariable Long id) {
        bookService.deleteBook(id);
        return "books";
    }
    
    0 讨论(0)
提交回复
热议问题