Servlet的Filter介绍
在Servlet作为过滤器使用时,它可以对客户的请求进行过滤处理,当它处理完成后,它会交给下一个过滤器处理,就这样,客户的请求在过滤链里一个个处理,直到请求发送到目标.如果过滤器不成功,则将试图转发到指定页面.
过滤器就像一扇门,客户端要和服务端的某个目标交互,必须通过这扇门.
典型filter应用
1 设置统一字符集 解决中文乱码问题.
request.setCharacterEncoding(“UTF-8");
post/get默认传输编码都是ISO8859-1
2 权限,比如检查会话是否有效。
如何编写Filter
开发一个自定义的Filter,需要实现Filter接口,Filter接口定义了以下的方法:
//由Web容器调用,销毁此Filter destroy() //由Web容器调用,初始化此Filter init(FilterConfig filterConfig) //具体过滤处理代码 doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
如何配置Filter
在web.xml文件中配置filter逻辑名 初始参数及拦截哪些pattern的请求。
<filter> <filter-name>EncodingFilter</filter-name> <filter-class>com.lessons.filter.EncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param>//通过FilterConfig类的getInitParameter("paramName") </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
过滤器范例:设置请求编码的过滤器
package com.app.servlet; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; /** * 设置请求编码的过滤器 * @author user */ public class EncodingFilter implements Filter { ServletContext application; private String basePath; public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest request = (HttpServletRequest)req; request.setCharacterEncoding("utf-8"); String path = request.getContextPath(); basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; application.setAttribute("bashPath", basePath); chain.doFilter(req, response);//交给下一个过滤器 } public void init(FilterConfig config) throws ServletException { // TODO Auto-generated method stub application = config.getServletContext(); } }
XML文件的配置
<filter> <filter-name>EncodingFilter</filter-name> <filter-class>com.app.servlet.EncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>