[英]Controller for delete request does not work
I'm really getting started with controllers for my small application, and i have this for now: 我的小型应用程序确实开始使用控制器,现在我有了这个:
@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";
}
the first one, is working properly, but the second doesn't, i have the following view for the first controller: 第一个,它工作正常,但是第二个没有,我对第一个控制器有以下看法:
<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>
like you see, i have two buttons here, one for edit the object and one for delete it. 如您所见,我在这里有两个按钮,一个用于编辑对象,一个用于删除对象。 Once deleted it, must redirect to
https://<my domain>/users
. 删除后,必须重定向到
https://<my domain>/users
。
The problem is, when i click on Delete
it just refresh the page and the object persist on the database, what is wrong here? 问题是,当我单击“
Delete
,仅刷新页面,并且对象保留在数据库中,这是什么问题?
DELETE
request like curl -X "DELETE" http://localhost:8080/my-app/users/18
but this didn't work. curl -X "DELETE" http://localhost:8080/my-app/users/18
这样的DELETE
请求,但这没有用。 I try another alternative using jQuery's ajax-method (but the same error persist): 我尝试使用jQuery的ajax方法的另一种方法 (但仍然存在相同的错误):
$.ajax({ url: '/users/' + someUserId, type: 'DELETE', success: function(result) { // Do something with the result } });
You have to use ajax to send a DELETE from the web page. 您必须使用ajax从网页发送DELETE。 The form tag itself only supports POST or GET.
表单标签本身仅支持POST或GET。 In your submit-Handler you have to suppress the default behaviour of the submit button, ie the submit of the form via GET or POST (
event.preventDefault()
): 在您的Submit-Handler中,您必须取消Submit按钮的默认行为,即通过GET或POST(
event.preventDefault()
)提交表单:
$("form").submit(function (event) {
event.preventDefault();
$.ajax({
url: '/users/' + someUserId,
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.