我真的开始使用我的小应用程序的控制器,我现在有这个:
@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";
}
Run Code Online (Sandbox Code Playgroud)
第一个,工作正常,但第二个没有,我有第一个控制器的以下视图:
<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>
Run Code Online (Sandbox Code Playgroud)
就像你看到的,我这里有两个按钮,一个用于编辑对象,一个用于删除它.删除后,必须重定向到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) {...}
Run Code Online (Sandbox Code Playgroud)
默认情况下,浏览器不支持此功能 - 浏览器仅支持POST和GET.要从浏览器发送DELETE请求,您必须使用JavaScript.
一种替代方法是使用例如jQuery的ajax方法
$.ajax({
url: '/users/' + someUserId,
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
Run Code Online (Sandbox Code Playgroud)
测试DELETE请求的一种方法是使用命令cUrl:
curl -X DELETE "http://myhost:port/users/someUserId"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1347 次 |
| 最近记录: |