16

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

html code:

<button id="delete" name="delete" th:onclick="@{'/foos/{id}'(id=${foo.id})}" th:method="delete">Delete</button>

controller code:

@RequestMapping(value="/foos/{id}", method = RequestMethod.DELETE)
@ResponseBody
public String delete(@PathVariable String id) {
    studentService.delete(id);
    return "Successfully deleted";
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
richersoon
  • 4,682
  • 13
  • 44
  • 74

2 Answers2

15

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>
Patrick
  • 12,336
  • 15
  • 73
  • 115
  • This is a boiler plate? Isn't? – richersoon Jul 14 '16 at 12:02
  • @richersoon No, isnt. I tried it out and it worked for me. I prefer the form way than using a button. And maybe it changed but my last information is that thymeleaf does not provide put and delete methods. So you need to help thymeleaf to understand what you want to do. Therefore the input field. – Patrick Jul 14 '16 at 12:46
  • 6
    when I try this, a post request is sent, although the value of the input is delete and the method is delete.... – JFFIGK Dec 06 '19 at 12:13
12

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";
}
Kirby
  • 15,127
  • 10
  • 89
  • 104
Raphael Roussis
  • 121
  • 1
  • 3