Search code examples
javaspring-bootspring-data-jpaspring-datathymeleaf

Spring Boot/JPA - How i can delete a record from database with DeleteMapping?


my problem is that I want to delete a record from the database by id by selecting a button, but when I click the button to delete the corresponding record with the parameter id I get this error:

>     HTTP Status 405 – Method Not Allowed
>     Type Status Report
>     
>     Message Method 'GET' is not supported.
>     
>     Description The method received in the request-line is known by the origin server but not supported by the target resource.

This is my code:

Thymeleaf:

<td>
   <a th:href="@{/delete/{idUser}(idUser=${user.idUser})}">Delete user</a>
</td>

Controller:

@DeleteMapping("/delete/{id}")
public String deleteMailbox(@PathVariable("id") Long id) {
    repo.deleteById(id);
    return "redirect:/userList?success";
}

Repository:

public interface UserRepository extends JpaRepository<User, Long> {

}

I don't know what I'm doing wrong in my code, or if I forget a specific command or parameter, I would appreciate any help you can give me.


Solution

  • The error is really self-descriptive. It says that Message Method 'GET' is not supported. This indicates that you are potentially trying to execute a GET request, but the GET endpoint is not registered... And indeed, that is the case, because of this line:

    <a th:href="@{/delete/{idUser}(idUser=${user.idUser})}">Delete user</a>
    

    This will execute the GET request and fail with 405. The solution would be simple, try executing the DELETE request instead of GET and it should work then.

    The other (not optimal) solution would be to change @DeleteMapping to @GetMapping, which should also work (but goes against REST principles!!).