1. 程式人生 > >springboot中delete請求方式的實現

springboot中delete請求方式的實現

前端

 $.ajax({
            type: 'DELETE',
            url: '/user/'+userId,
            ...
       })

後端

 @DeleteMapping("{userId}")
 public ResponseEntity<Void> deleteUser( @PathVariable String userId){}

此方法適合在springboot中,此方法對PUT請求亦可.

1.SpringBoot已經預設引入了HiddenHttpMethodFilter,可在SpringBoot啟動日誌裡看到該Filter的啟動資訊。

2.Delete方式有Entity Body,但是該方法傳遞Entity Body沒有明確定義的語義,所以有些伺服器實現會丟棄/忽略DELETE請求的entity body,或者拒絕該請求。所以Delete請求中,不要把資料放到Entity Body中。

3.非常坑的一點是,GET沒有Entity Body,在ajax中寫入data來傳參,會直接把引數拼接到url後面。DELETE方式卻不可以。所以使用DELETE方式請求時,要手動將引數拼接到url中,而非寫到data中。

若為非springboot則用其他的方式:

SpringMVC中對PUT DELETE方式不支援,要加入HiddenHttpMethodFilter,在前端將PUT DELETE請求改為type:“POST”,data:{_method:"DELETE}才可以接收,此處不詳細講述。