HiddenHttpMethodFilter过滤器

       前言

        SpringMVC中HiddenHttpMethodFilter过滤器的使用


HiddenHttpMethodFilter

        在SpringMVC中。HiddenHttpMethodFilter是一种过滤器也属于一种拦截器。用于过滤用户提交form表单时的Rest风格方式。可以将这些请求转换为标准的http方法。

如:post、put、get、delete、options、trace、head

        HiddenHttpMethodFilter的父类是OncePerRequestFilter。它继承了父类的doFilterInternal方法,工作原理是将jsp页面的form表单的method属性值在doFilterInternal方法中转化为标准的Http方法,即GET、POST、 HEAD、OPTIONS、PUT、DELETE、TRACE,然后到Controller中找到对应的方法。

需要注意的是,由于doFilterInternal方法只对method为post的表单进行过滤。并且在写参数时使用小写:post、put…

//thymeleaf模式编写。跳转不同的Controller
<form action="#" th:action="@{/index/save}" method="post">
   <input type="hidden" name="_method" value="put" th:if="${user!=null}"/>
</form>

同时SpringMVC中,HiddenHttpMethodFilter必须作用于dispatcher前,所以在web.xml中配置HiddenHttpMethodFilter时,需参照如下代码:

<filter>  
  <filter-name>HiddenHttpMethodFilter</filter-name>  
    <filter-class>
        org.springframework.web.filter.HiddenHttpMethodFilter
    </filter-class>  
 </filter>  
 <filter-mapping>  
    <filter-name>HiddenHttpMethodFilter</filter-name>  
        <servlet-name>spring</servlet-name>  
 </filter-mapping>
  <servlet>
     <servlet-name>spring</servlet-name>
      <servlet-class>
           org.springframework.web.servlet.DispatcherServlet
       </servlet-class>
    <init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath:spring.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
     <servlet-name>spring</servlet-name>
     <url-pattern>*.html</url-pattern>
   </servlet-mapping>

而在SpringBoot中,HiddenHttpMethodFilter的配置参数以及在底层已经实现了。我们只需要将标签写上即可。