您的位置:首页 > 其它

web.xml有关过滤器的配置

2017-02-21 15:10 399 查看
1:过滤器HiddenHttpMethodFilter

      浏览器中form表单仅仅支持get和post请求,而delete、put 等method并不支持,spring3.0添加一个过滤器,可以将这些请求转化为标注的http请求,使得支持get、put、delete、post请求,该过滤器为HiddenHttpMethodFilter。

     过滤器HiddenHttpMethodFilter的父类是OncePerRequestFilter,他继承了父类的doFilterInternal的方法,工作原理是:将jsp页面的from表单的method属性值在doFilterInternal方法中转化为标准的http方法,即get、post、delete、put、head等。然后在对应的controller中找到对应的方法。例如:在使用注解时我们可能会在controller用于@RequestMapping(value
= "list", method = RequestMethod.PUT),所以如果你的表单中使用的是<form method= "put">这个表单会被提交到method =“put”的方法中。

需要注意的是:由于doFilterInternal方法只能对method为post表单进行过滤,所以必须在页面中设置

<form action="..." method="post">  

        <input type="hidden" name="_method" value="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:spring/educate-api-servlet.xml</param-value>  

</init-param>  

lt;/servlet>  

      <servlet-mapping>  

<servlet-name>spring</servlet-name>  

<url-pattern>*.html</url-pattern>  

lt;/servlet-mapping>  



2:字符过滤器  CharacterEncodingFilter

<filter>

        <filter-name>CharacterEncodingFilter</filter-name>

        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

        <init-param>

          <param-name>encoding</param-name>

          <param-value>utf-8</param-value>

        </init-param>

      </filter>

    <filter-mapping>

        <filter-name>CharacterEncodingFilter</filter-name>

        <url-pattern>/*</url-pattern>

    </filter-mapping>

3:HttpPutFormContentFilter过滤器

Spring3.0中获取put表单的参数-值还有另一种方法,即使用HttpPutFormContentFilter过滤器。

        HttpPutFormContentFilter过滤器的作为就是获取put表单的值,并将之传递到Controller中标注了method为RequestMethod.put的方法中。

        在web.xml中配置HttpPutFormContentFilter的代码类似如下:

<filter>  

    <filter-name>httpPutFormcontentFilter</filter-name>  

    <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>  

</filter>  

<filter-mapping>  

    <filter-name>httpPutFormContentFilter</filter-name>  

    <url-pattern>/*</url-pattern>  

</filter-mapping>  

        需要注意的是,该过滤器只能接受enctype值为application/x-www-form-urlencoded的表单,也就是说,在使用该过滤器时,form表单的代码必须如下:

<form action="" method="put" enctype="application/x-www-form-urlencoded">  

......  

</form>  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: