gpt4 book ai didi

java - 删除 Controller 不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:01:43 26 4
gpt4 key购买 nike

我真的开始为我的小应用程序使用 Controller ,我现在有这个:

@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";

}

第一个可以正常工作,但第二个不能,我对第一个 Controller 有以下 View :

<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 时它只是刷新页面并且对象保留在数据库中,这里有什么问题吗?

  • 我尝试发送 DELETEcurl -X "DELETE" http://localhost:8080/my-app/users/18这样的请求但这没有用。

最佳答案

有一堆methods available通过 HTTP 通信时。最常见的是 GET、PUT、POST 和 DELETE。

在你的 Controller 中你声明你期待一个删除请求:

@RequestMapping(value="/users/{id}", method=RequestMethod.DELETE)
public String deleteMemeber(@PathVariable Integer id) {...}

浏览器默认不支持 - 浏览器仅支持 POST 和 GET。为了从浏览器发送删除请求,您必须使用 JavaScript。

一种替代方法是使用例如jQuery's ajax-method

$.ajax({
url: '/users/' + someUserId,
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});

测试删除请求的一种方法是使用命令 cUrl:

curl -X DELETE "http://myhost:port/users/someUserId"

关于java - 删除 Controller 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27675013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com