瀏覽器form表單只支持GET與POST請求涯呻,而DELETE、PUT等method并不支持腻要,spring3.0添加了一個過濾器复罐,可以將這些請求轉(zhuǎn)換為標準的http方法,使得支持GET闯第、POST市栗、PUT與DELETE請求,該過濾器為HiddenHttpMethodFilter咳短。
HiddenHttpMethodFilter的父類是OncePerRequestFilter填帽,它繼承了父類的doFilterInternal方法,工作原理是將jsp頁面的form表單的method屬性值在doFilterInternal方法中轉(zhuǎn)化為標準的Http方法咙好,即GET,篡腌、POST、 HEAD勾效、OPTIONS嘹悼、PUT、DELETE层宫、TRACE杨伙,然后到Controller中找到對應(yīng)的方法。例如萌腿,在使用注解時我們可能會在Controller中用于@RequestMapping(value = "list", method = RequestMethod.PUT)限匣,所以如果你的表單中使用的是<form method="put">,那么這個表單會被提交到標了Method="PUT"的方法中毁菱。
需要注意的是米死,由于doFilterInternal方法只對method為post的表單進行過濾锌历,所以在頁面中必須如下設(shè)置:
<form action="..." method="post">
<input type="hidden" name="_method" value="put" />
</form>
而不使用:
<form action="..." method="put">
...
</form>
同時,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:dispatcher.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
作為Filter,也可以在web.xml中配置HiddenHttpMethodFilter的參數(shù)物喷,可配置的參數(shù)為methodParam卤材,值必須為GET,、POST脯丝、 HEAD商膊、OPTIONS、PUT宠进、DELETE晕拆、TRACE中的一個。