1、Filter(过滤器)
JavaWeb三大组件之一
特点:在一组资源(Jsp、Servlet、.css、.html等等)的前面执行
作用:过滤器有拦截请求的能力
可使请求得到目标资源,也可阻止请求得到目标资源
Filter接口中的方法:
void init(FilterConfig)
创建之后,马上执行;Filter会在服务器启动时就创建!
void destory()
销毁之前执行!在服务器关闭时销毁
void doFilter(ServletRequest,ServletResponse,FilterChain)
每次过滤时都会执行
Filter是单例的!
Filter中的相关类
FilterConfig类
方法:
获取初识化参数: .getInitParameter();
获取过滤器名称: .getFilterName();
获取application .getServletContext();
FilterChain
方法:
放行(不拦截):doFilter(ServletRequest req, ServletResponse res); 。
编写过滤器示例
1)写一个类实现Filter接口
2)在web.xml中进行配置
//1)写一个类实现Filter接口
public class AFilter implements Filter {
/**
* 创建之后马上执行,用来做初始化!
*/
public void init(FilterConfig filterConfig) throws ServletException {
}
/**
* 每次过滤时都会执行
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("AFilter#start");
chain.doFilter(request, response);//放行!
System.out.println("AFilter#end");
}
/**
* 销毁之前执行,用来做对非内存资源进行释放
*/
public void destroy() {
}
}
//在web.xml中进行配置
<filter>
<filter-name>AFilter</filter-name>
<filter-class> web.filter.AFitler </filter-class>
</filter>
<filter-mapping>
<filter-name>AFilter</filter-name>
<url-pattern>/AServlet</url-pattern> //阻止的路径 此时过滤/AServlet
</filter-mapping>
2、过滤器(多个)的执行顺序、拦截方式、应用场景
多个过滤器时的执行顺序:
<filter-mapping>的配置顺序决定了过滤器的执行顺序
涉及方法:
FilterChain#doFilter()方法:
执行下一个过滤器,或执行目标资源(无下一个过滤器时)。
过滤器的四种拦截方式(默认只拦截request)
标签格式为<dispatcher> 拦截方式</dispatcher>
拦请求:DISPATCHER
拦转发:FORWORD
拦包含:INCLUDE
拦错误: ERROR
需要在web.xml# <filter-mapping>中进行配置
eg: 拦截AServlet中的转发
<filter-mapping>
<filter-name>BFilter</filter-name>
<url-pattern>/AServlet</url-pattern>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
过滤器的应用场景:
1)执行目标资源之前做预处理工作. eg:设置编码
2)通过条件判断是否放行。 eg:校验用户是否已经登陆
3)目标资源执行后,做一些后续特殊处理工作。 eg: 处理输出数据
3、案例一:分ip统计网站的访问次数
分析:
1)统计工作需要在所有之前都执行,那么就需要放进Filter中了
2)过滤器不做拦截操作
3)需要有装载统计数据的容器 这里使用Map<String,Integer>
4)Map创建时机:在服务器启动时完成创建 使用ServletContextListener监听器
5)Map保存位置:保存到ServletContext 原因如下
Map需要在页面中使用,打印数据
Map需要在Filter中来保存数据