今天看DispatcherServlet的源碼的時候看到了Spring中默認攔截器,了解了一下用處,在這簡單的記錄一下
瀏覽器支持GET和POST的提交請求方式,如果要用到PUT或DELETE,就要有過濾器的支持才能實現,Spring中的HiddenHttpMethodFilter就是來支持這個功能的。
實現方式是前端在form表單中添加一個隱藏域 <input type="hidden" name="_method" value="DELETE"/> ,下面簡單試驗一下,我用的是SpringBoot來測試的,啟動時就配置好了HiddenHttpMethodFilter,如果是SpringMvc的話需要在web.xml中配置,詳情網上一堆。
前端頁面 test.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <title>Title</title> </head> <body> <form action="/test/emp" method="post"> <input type="hidden" name="_method" value="DELETE"/> id:<input name="id" type="text" /> name:<input name="name" type="text" /> sex:<input name="sex" type="text" /> date:<input name="date" type="text" /> address:<input name="address" type="text" /> <input type="submit" value="查"/> </form> </body> </html>
Controller層
package com.example.controller; import com.example.bean.JsonResult; import com.example.demo.Article; import com.example.demo.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping("/test") public class TestController { @RequestMapping(value = "/emp", method = RequestMethod.DELETE) @ResponseBody public void testPut(User user){ System.out.println(user); } }
在瀏覽器上調用一下
改成PUT的話了也一樣