2017-08-14 79 views
0

我在我的ajax中寫了一個請求(method:delete)。我在我的控制器中使用了一個deleteMapping。當我觸發這個請求時,我得到了一個400錯誤。但在瀏覽器中我可以看到數據專案編號enter image description hereSpring controller必需字符串參數不存在

控制檯說Required String parameter 'projectId' is not present

總日誌

2017-08-14 13:06:11.296 WARN 8584 --- [nio-8080-exec-3] o.s.web.servlet.PageNotFound    : Request method 'DELETE' not supported 
2017-08-14 13:06:11.296 WARN 8584 --- [nio-8080-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'DELETE' not supported 

2017-08-14 12:32:57.239 WARN 8584 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'projectId' is not present 

這裏是AJAX

$('#delete-project-btn').on('click', function() { 
    if (cur != null) { 
     alert(cur); 
     if(window.confirm('sure?')) { 
      $.ajax({ 
       url : '/index/'+cur, 
       type : 'delete', 
       dataType : 'text', 
       data : { 
        projectId : cur 
       },    
      }); 
     } 
    } 

}) 

和我的controller

 @DeleteMapping("/index/{projectId}") 
    public String deleteProject(@PathVariable("projectId") int id) { 
     System.out.println(id); 
//  projectRepository.delete(Integer.valueOf(id)); 
     return "redirect:/index"; 
    } 

問題在哪裏?

+2

在你的Ajax請求,你應該通過專案編號爲的一部分請求參數不請求正文。 – Barath

回答

4

按照下面的評論鏈接,

如果DELETE請求包括實體主體,身體被忽略

$('#delete-project-btn').on('click', function() { 
    if (cur != null) { 
     alert(cur); 
     if(window.confirm('sure?')) { 
      $.ajax({ 
       url : '/index?projectId='+cur, 
       type : 'delete', 
       dataType : 'text' 

      }); 
     } 
    } 

}) 
+0

閱讀完整的討論在這裏https://stackoverflow.com/questions/299628/is-an-entity-body-allowed-for-an-http-delete-request – Barath

+0

如何更改我的控制器,以獲得該ID? –

+0

我認爲你的控制器是正確的,只是嘗試更改上述更新的AJAX請求url – Barath

相關問題