Filter:过滤器,用来过网站的数据;
作用
1. 处理中文乱码
2.登录验证
Filter开发步骤
1.导包
2.编写过滤器
1.导包不要错
2.实现Filter接口,重写对应的方法即可
public class filterDemo1 implements Filter {
//初始化:web服务器启动,就以及初始化了,随时等待过滤对象出现!
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println ("filterDemo已经初始化了");
}
//filterChain:链
//1.过滤中的所有代码,在过滤特定请求的时候都会执行!
//2.必须要让过滤器继续同行
// filterChain.doFilter (servletRequest,servletResponse);
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//处理编码
servletRequest.setCharacterEncoding ("utf-8");
servletResponse.setCharacterEncoding ("utf-8");
servletResponse.setContentType ("text/html;charset=UTF-8");
System.out.println ("filterDemo执行前......");
//让我们的请求继续走,如果不写,程序到这里就被拦截停止!
filterChain.doFilter (servletRequest,servletResponse);
System.out.println ("filterDemo执行后......");
}
//销毁:web服务器关闭的时候,过滤会销毁
public void destroy() {
System.out.println ("filterDemo已经销毁了");
}
}
3.在web.xml中配置Filter
<filter>
<filter-name>filterDemo1</filter-name>
<filter-class>com.bubbles.filter.filterDemo1</filter-class>
</filter>
<filter-mapping>
<filter-name>filterDemo1</filter-name>
<url-pattern>/server/*</url-pattern>
</filter-mapping>