(1)概念:
它是服务器组件,用来过滤用户请求和响应信息。
(2)原理:
过滤器相当于安检人员,将请求按倒在服务器的大门外摩擦摩擦,直到满足口味了才让请求进门。
(3)filter声明周期
1.启动web服务器时初始化,执行init()
2.用户请求的时候拦截请求,执行FilterChain.doFilter()
3.关闭web服务器的时,执行destroy()
(4)下面写一个字符过滤器为例
第一步:在web项目Filte下新建一个过滤器叫fristFilter类,实现Filter接口。
package 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 fristFilter implements Filter {
protected FilterConfig filterConfig;
protected String encoding;
@Override
public void destroy() {
System.out.println("3:destroy()在tomcat关闭时被执行。");
filterConfig=null;
encoding=null;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("2:这是doFilter(),处理请求编码信息");
if (encoding!=null) {
request.setCharacterEncoding(encoding);
} else {
request.setCharacterEncoding("utf-8");
}
System.out.println("你当前的字符编码格式是:"+request.getCharacterEncoding());
chain.doFilter(request, response);//传递过滤链
}
@Override
public void init(FilterConfig config) throws ServletException {
System.out.println("1:init()在tomcat启动时被执行。");
this.filterConfig=config;
this.encoding=config.getInitParameter("encoding");
}
}
第二步:web.xml中填写filter配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>setCharacterEncoding</filter-name>
<filter-class>filter.fristFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>setCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
第三步:启动项目,在控制台输出展示