GET请求而不是DELETE请求?

huangapple go评论58阅读模式
英文:

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(&quot;/delete/{id}&quot;)
    public String deleteStudent(@PathVariable Long id) {
        this.studentService.deleteStudent(id);

        return &quot;redirect:/students&quot;;
    }

In students.html

&lt;a th:href=&quot;@{&#39;/students/delete/&#39; + ${student.id}}&quot; class=&quot;btn btn-danger&quot;&gt;Delete&lt;/a&gt;

答案1

得分: 1

M. Deinum在评论中说,使用html &lt;a href,你正在进行http GET请求。使用html form,你可以进行http GET或POST请求。所以在你的情况下,将@DeleteMapping(&quot;/delete/{id}&quot;)更改为@PostMapping(&quot;/delete/{id}&quot;)并使用html &lt;form method=&quot;post&quot;有一定道理。

如果你想使用http DELETE,你将需要使用javascript。

英文:

As M. Deinum said in comments, with html &lt;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(&quot;/delete/{id}&quot;) to @PostMapping(&quot;/delete/{id}&quot;) and using html &lt;form method=&quot;post&quot; kind of makes sense.

If you want to use http DELETE, you will have to use javascript.

huangapple
  • 本文由 发表于 2023年4月16日 23:37:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76028695.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定