servlet作为过滤器时,他可以对客户的请求进行过滤处理,当它处理完后在交给其他的过滤器处理,知道请求发到最终目标。它还要在web.xml当中配置。
注意事项:开发filter要实现filter接口,在接口当中定义了如下方法:
destory()
//由web服务器调用,销毁此过滤器
i nit(filterconfig config)
//由服务器掉有,初始话次过滤器
doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
//具体处理的代码
例如:用来处理中文的过滤器具体代码
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Encoding implements Filter
{
private String targetEncoding="gb2312";
protected FilterConfig filterConfig;
public void init(FilterConfig config)throws ServletException
{
this.filterConfig=config;
this.targetEncoding=config.getInitParame("encoding");
}
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws IOException,ServletException
{
HttpServletRequest req=(HttpServletRequest)request;
req.serCharcterEncoding(targetEncoding);
chain.doFiletr(request,response);
}
public void destroy()
{
this.filterConfig=null;
}
}
让我们再看看web.xml文件
......
<web-app>
<filter><!-可以有多个这样的标签-->
<filter-name>encoding</filter-name>
<filter-class>EncodingFilter</filter-name>
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
<filter-mapping><!-可以有多个这样的标签-->
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern><!-用来过滤所有的请求-->
</filter-mapping>
</web-app>
现在大家可以知道过滤器是如何工作的了吧!