英文:
GET request instead of DELETE?
问题
使用下面显示的代码,我无法删除学生,因为当我点击删除按钮时,它会抛出“方法不允许”错误(状态=405)。
我发现很多人使用GET请求来管理这个,但这不是一个好的做法吗?我只想删除具有该ID的学生并保持在同一页(我会在修复此问题后稍后管理删除验证)。为什么相同的代码在GetMapping下工作而在DeleteMapping下不工作?
在studentController中
@DeleteMapping("/delete/{id}")
public String deleteStudent(@PathVariable Long id) {
this.studentService.deleteStudent(id);
return "redirect:/students";
}
在students.html中
<a th:href="@{'/students/delete/' + ${student.id}}" class="btn btn-danger">删除</a>
英文:
Using the code shown below, I can't delete a student because when I click the delete button, it throws a Method Not Allowed error (status=405)
I found out that many people use GET request instead of DELETE to manage this, but isn't it a bad practice? I just only want to delete the student with that id and stay at the same page (I'll manage delete validations later after I fix this). Why does the same code work with GetMapping but not with DeleteMapping?
In studentController
@DeleteMapping("/delete/{id}")
public String deleteStudent(@PathVariable Long id) {
this.studentService.deleteStudent(id);
return "redirect:/students";
}
In students.html
<a th:href="@{'/students/delete/' + ${student.id}}" class="btn btn-danger">Delete</a>
答案1
得分: 1
M. Deinum在评论中说,使用html <a href
,你正在进行http GET请求。使用html form
,你可以进行http GET或POST请求。所以在你的情况下,将@DeleteMapping("/delete/{id}")
更改为@PostMapping("/delete/{id}")
并使用html <form method="post"
有一定道理。
如果你想使用http DELETE,你将需要使用javascript。
英文:
As M. Deinum said in comments, with html <a href
you're doing http GET request. With html form
you can do http GET or POST requests. So in your case changing @DeleteMapping("/delete/{id}")
to @PostMapping("/delete/{id}")
and using html <form method="post"
kind of makes sense.
If you want to use http DELETE, you will have to use javascript.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论