2015-02-08 25 views
0

我真的開始使用控制器爲我的小應用程序,我有這個現在:控制器刪除請求不起作用

@RequestMapping("https://stackoverflow.com/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="https://stackoverflow.com/users/{id}", method=RequestMethod.DELETE) 
public String deleteMemeber(@PathVariable Integer id) { 

    userService.delete(id); 

    return "redirect:users"; 

} 

第一位的,工作正常,但第二個沒有按」 T,我對第一個控制器的以下觀點:

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

就像你看到的,我這裏有兩個按鈕,一個要編輯的對象,一個用於刪除。 一旦刪除它,必須重定向到https://<my domain>/users

問題是,當我點擊Delete它只是刷新頁面和對象持久存在數據庫,這裏有什麼問題?

  • 我嘗試發送一個DELETE請求像curl -X "DELETE" http://localhost:8080/my-app/users/18但這沒有奏效。
  • 我嘗試使用jQuery's ajax-method另一種選擇(但同樣的錯誤仍然存​​在):

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

@湯姆我的錯,是以前的版本。修復。 – Vercryger 2015-02-08 21:07:01

+0

您是否嘗試過使用'method = RequestMethod.POST'來代替? – Tom 2015-02-08 21:11:33

+0

是的,行爲是一樣的。 – Vercryger 2015-02-08 21:20:54

回答

1

你必須使用AJAX來發送從網頁中刪除。表單標籤本身只支持POST或GET。在您提交處理程序,你必須抑制提交按鈕的默認行爲,即通過GET或POST(event.preventDefault())的形式提交:

$("form").submit(function (event) { 
     event.preventDefault(); 

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