Spring MVC過濾器-HiddenHttpMethodFilter

    瀏覽器form表單只支持GET與POST請求,而DELETE、PUT等method並不支持,spring3.0添加了一個過濾器,能夠將這些請求轉換爲標準的http方法,使得支持GET、POST、PUT與DELETE請求,該過濾器爲HiddenHttpMethodFilter。html

    HiddenHttpMethodFilter的父類是OncePerRequestFilter,它繼承了父類的doFilterInternal方法,工做原理是將jsp頁面的form表單的method屬性值在doFilterInternal方法中轉化爲標準的Http方法,即GET,、POST、 HEAD、OPTIONS、PUT、DELETE、TRACE,而後到Controller中找到對應的方法。例如,在使用註解時咱們可能會在Controller中用於@RequestMapping(value = "list", method = RequestMethod.PUT),因此若是你的表單中使用的是<form method="put">,那麼這個表單會被提交到標了Method="PUT"的方法中。web

        須要注意的是,因爲doFilterInternal方法只對method爲post的表單進行過濾,因此在頁面中必須以下設置:spring

<form action="..." method="post">
        <input type="hidden" name="_method" value="put" />
        ......
</form>

而不是使用:瀏覽器

<form action="..." method="put">
        ......
</form>

同時,HiddenHttpMethodFilter必須做用於dispatcher前,因此在web.xml中配置HiddenHttpMethodFilter時,需參照以下代碼:app

<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:dispatcher.xml</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>

一樣的,做爲Filter,能夠在web.xml中配置HiddenHttpMethodFilter的參數,可配置的參數爲methodParam,值必須爲GET,、POST、 HEAD、OPTIONS、PUT、DELETE、TRACE中的一個。jsp

相關文章
相關標籤/搜索