快速入门
1、新建一个类,实现Filter接口
2、实现doFilter()方法,打印一句话,来证明能够进行拦截
3、在web.xml中进行配置(参照Servlet配置)
4、访问一个页面,看看能不能拦截
1>
package com.test.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class Demo1Filter implements Filter {
private FilterConfig filterConfig;
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("Demo1过滤前");
System.out.println(filterConfig.getInitParameter("param1"));
chain.doFilter(request, response);//放行。让其走到下个链或目标资源中
System.out.println("Demo1过滤后");
}
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("初始化了");
this.filterConfig = filterConfig;
}
public void destroy() {
System.out.println("销毁了");
}
}
2>在web.xml中进行配置
<filter>
<filter-name>Demo1Filter</filter-name>
<filter-class>com.itheima.filter.Demo1Filter</filter-class>
<init-param>
<param-name>param1</param-name>
<param-value>value在这里呢</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Demo1Filter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher> <!-- 没有配置dispatcher就是默认request方式的 -->
<dispatcher>FORWARD</dispatcher>
<dispatcher>ERROR</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>