过滤器如何编写
1.写一个类实现Filter接口
2.在web.xml中配置
1.Filter 接口
public class filter implements Filter{
/**
* 销毁前执行, 服务器关闭时销毁
*/
@Override
public void destroy() {
}
/**
* 每次过滤时都会执行
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
}
/**
* 创建之后,马上执行,Filter在服务器启动时就创建
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
2.web.xml 配置
<filter>
<filter-name>AFilter</filter-name>
<filter-class>com.mlj.filter</filter-class>
</filter>
<filter-mapping>
<filter-name>AFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Filter 特性: 单例
FilterConfig -->与ServletConfig 相似
- getInitParameter(arg0) 获取初始化参数值
- getFilterName() 获取过滤器名称
- getServletContext() 获取 上下文
FilterChain 过滤链
- doFilter(request, response) 放行
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("我在过滤");
chain.doFilter(request, response); //放行
System.out.println("我回来了");
}
chain.doFilter(request, response); 执行后,跳转到servlet,servlet执行结束后回来继续执行filter后续代码