1. 什么是过滤器
拦截不符合过滤要求的请求,使其无法到达目的地。
执行过程
主要用在:统一认证,统一编码设置
2. 创建过滤器
两种方式:与 servlet 雷同
① 注解方式 (/* 拦截所有请求)
@WebFilter(filterName = "MyFilter",urlPatterns = "/*")
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//初始化---只会执行一次
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//过滤的业务处理代码
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
//放行
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("------再次经过过滤器~~~~~~~~~~~~");
}
@Override
public void destroy() {
//销毁方法--当服务器重启或关闭时
}
}
②web.xml 方式
<!--注册过滤器-->
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.ykq.filter.MyFilter</filter-class>
</filter>
<!--过滤规则-->
<filter-mapping>
<filter-name>MyFilter</filter-name>
<!--
/*:表示拦截所有的请求
/views/*: 只拦截包含views/资源
/*.do: 拦截请求后缀未.do资源
-->
<url-pattern>/*</url-pattern>
</filter-mapping>
3. 编码过滤器
public class EncodingFilter implements Filter {
private String encoding="gbk";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//初始化---只会执行一次
encoding=filterConfig.getInitParameter("encoding");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding(encoding); //ISO-8859-1 java源码一旦写完就无法修改
servletResponse.setCharacterEncoding(encoding);
//放行
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
//销毁方法--当服务器重启或关闭时
}
}
使用 web.xml 方式
<!--注册过滤器-->
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.ykq.filter.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<!--过滤规则-->
<filter-mapping>
<filter-name>MyFilter</filter-name>
<!--
/*:表示拦截所有的请求
/views/*: 只拦截包含views/资源
/*.do: 拦截请求后缀未.do资源
-->
<url-pattern>/*</url-pattern>
</filter-mapping>