簡體   English   中英

刪除控制器不起作用

[英]Delete controller is not working

我真的開始使用我的小應用程序的控制器,我現在有這個:

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

正如其他人所提到的,您實際上並沒有發送HTTP DELETE請求。 您的刪除按鈕是表單帖子的一部分,因此當您提交表單時,它實際上會發送HTTP POST請求。 其他人已經演示了一些調用DELETE(Ajax和CURL)的方法,但我發現最簡單的方法是在你喜歡的瀏覽器上安裝一個插件。 如果您使用的是Chrome,則可以嘗試使用Advanced Rest Client擴展等功能。

正如其他人所說,你的html表格將發送POST,因為這是你的行動。

如果你想保留按鈕並在沒有javascript(AJAX調用)的情況下進行刪除,那么你應該嘗試更改java端的url模式,並將刪除按鈕html分成單獨的形式

@RequestMapping(value =“/ users / delete / {id}”,method = RequestMethod.POST)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM