1

I have a simple webapp showing list of students with add and delete button like this: enter image description here

index.html - table

<tr th:each="student : ${students}">
     <td th:text="${student.firstName} + ' ' + ${student.lastName}"></td>
     <td th:text="${student.email}"></td>
     <td th:text="${student.department}"></td>
     <td><a th:href="@{/delete/{id}(id=${student.id})}" class="btn btn-danger">Delete</a></td>
</tr>

IndexController.java - for deleting

@GetMapping("/delete/{id}")
    public String deleteStudent(@PathVariable Long id)
    {
        studentService.deleteStudentById(id);
        return "redirect:/";
    }

My question - why it has to be @GetMapping in my controller that will delete a student using Delete button on the www page? When I had @DeleteMapping there (as I thought it should be) I couldn't delete a student with Delete button on the www page. There was a 405 error while doing it but via Postman with delete method selected I could delete it.

Kiran Mistry
  • 2,614
  • 3
  • 12
  • 28
wojciechw
  • 71
  • 1
  • 13
  • 4
    Because the delete button is simply a link that is styled to look like a button. Links always requested using GET method. – Alan Hay Jul 29 '19 at 13:24
  • 1
    I think you can add `method="delete"` to your `a` tag. The default is a get request. – marstran Jul 29 '19 at 13:24
  • 1
    You can use something other than GET for links??https://stackoverflow.com/questions/6926512/how-to-specify-delete-method-in-a-link-or-form – Alan Hay Jul 29 '19 at 13:26
  • Ok now I understand, links = get method by default. Thx for answers. – wojciechw Jul 29 '19 at 13:31
  • 1
    As a side note: if you already trying to use `HTTP DELETE` word, there's no use in having `/delete/` as part of the URI on top of that, you should just go for `@Delete("{id}")`. – M. Prokhorov Jul 29 '19 at 13:36

1 Answers1

0

@DeleteMapping annotation needs a th: method = "delete" to work.

<td>
      <form  th: action = "@ {/delete/{id}(id=${student.id})}"  th: method = "delete" >
      <input  class = "btn btn-default btn-xs"  type = "submit" = Valeur "Supprimer"  /> 
      </ form> 
</td>
becher henchiri
  • 618
  • 4
  • 10