我的小型应用程序确实开始使用控制器,现在我有了这个:
@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 method="post">
...
<button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-pencil"></span> Edit</button>
<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
这样的请求,但这没有用。通过HTTP进行通信时,可以使用多种方法。最常见的是GET,PUT,POST和DELETE。
在您的控制器中,您声明您期望一个DELETE请求:
@RequestMapping(value="/users/{id}", method=RequestMethod.DELETE)
public String deleteMemeber(@PathVariable Integer id) {...}
默认情况下,浏览器不支持此功能-浏览器仅支持POST和GET。为了从浏览器发送DELETE请求,您必须使用JavaScript。
一种替代方法是使用例如jQuery的ajax方法
$.ajax({
url: '/users/' + someUserId,
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
测试DELETE请求的一种方法是使用命令cUrl:
curl -X DELETE "http://myhost:port/users/someUserId"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句