删除请求的控制器不起作用
Controller for delete request does not work
我真的开始为我的小应用程序使用控制器,我现在有这个:
@RequestMapping("/users/{id}")
public ModelAndView showMemeber(@PathVariable Integer id) {
ModelAndView mav = new ModelAndView("user/show");
mav.addObject("title", "Show User");
mav.addObject("user", userService.findById(id));
return mav;
}
@RequestMapping(value="/users/{id}", method=RequestMethod.DELETE)
public String deleteMemeber(@PathVariable Integer id) {
userService.delete(id);
return "redirect:users";
}
第一个可以正常工作,但第二个不能,我对第一个控制器有以下看法:
<div class="panel-heading">Personal information</div>
<div class="panel-body">
<form>
...
<button type="submit" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete {{ user.username }}?')"><span class="glyphicon glyphicon-remove"></span> Delete</button>
</form>
</div>
如您所见,我这里有两个按钮,一个用于编辑对象,一个用于删除对象。
一旦删除它,必须重定向到 https://<my domain>/users
.
问题是,当我单击 Delete
时,它只是 刷新了 页面,并且对象保留在数据库中,这里有什么问题吗?
- 我尝试发送
DELETE
请求,例如 curl -X "DELETE" http://localhost:8080/my-app/users/18
,但这没有用。
我尝试使用 jQuery's ajax-method 的另一种替代方法(但仍然存在相同的错误):
$.ajax({
url: '/users/' + someUserId,
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
您必须使用 ajax 从网页发送删除。表单标签本身只支持 POST 或 GET。在您的提交处理程序中,您必须抑制提交按钮的默认行为,即通过 GET 或 POST (event.preventDefault()
):
提交表单
$("form").submit(function (event) {
event.preventDefault();
$.ajax({
url: '/users/' + someUserId,
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
}
我真的开始为我的小应用程序使用控制器,我现在有这个:
@RequestMapping("/users/{id}")
public ModelAndView showMemeber(@PathVariable Integer id) {
ModelAndView mav = new ModelAndView("user/show");
mav.addObject("title", "Show User");
mav.addObject("user", userService.findById(id));
return mav;
}
@RequestMapping(value="/users/{id}", method=RequestMethod.DELETE)
public String deleteMemeber(@PathVariable Integer id) {
userService.delete(id);
return "redirect:users";
}
第一个可以正常工作,但第二个不能,我对第一个控制器有以下看法:
<div class="panel-heading">Personal information</div>
<div class="panel-body">
<form>
...
<button type="submit" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete {{ user.username }}?')"><span class="glyphicon glyphicon-remove"></span> Delete</button>
</form>
</div>
如您所见,我这里有两个按钮,一个用于编辑对象,一个用于删除对象。
一旦删除它,必须重定向到 https://<my domain>/users
.
问题是,当我单击 Delete
时,它只是 刷新了 页面,并且对象保留在数据库中,这里有什么问题吗?
- 我尝试发送
DELETE
请求,例如curl -X "DELETE" http://localhost:8080/my-app/users/18
,但这没有用。 我尝试使用 jQuery's ajax-method 的另一种替代方法(但仍然存在相同的错误):
$.ajax({ url: '/users/' + someUserId, type: 'DELETE', success: function(result) { // Do something with the result } });
您必须使用 ajax 从网页发送删除。表单标签本身只支持 POST 或 GET。在您的提交处理程序中,您必须抑制提交按钮的默认行为,即通过 GET 或 POST (event.preventDefault()
):
$("form").submit(function (event) {
event.preventDefault();
$.ajax({
url: '/users/' + someUserId,
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
}