今天看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的话了也一样