一、filter过滤器简介
主要对JavaWeb应用的资源进行过滤。
对请求和响应的进行处理
二、过滤器编码步骤
a、编写一个类实现javax.servlet.Filter接口。在doFilter方法中编写过滤代码 过滤范围内的资源每次访问都会执行这个方法
b、在web.xml中配置那些资源需要经过过滤器
<span style="white-space:pre"> </span><filter>
<filter-name>SetCharacterEncodingFilter</filter-name>
<filter-class>test.filter.SetCharacterEncodingFilter</filter-class> <span style="color:#ff0000;">//类全名 </span>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncodingFilter</filter-name> <span style="color:#ff0000;"><strong>如果有多个过滤器是根据这个标签的顺序分前后的</strong></span>
<url-pattern>/*</url-pattern> <span style="color:#ff0000;">//配置应用范围 /*代表所有</span>
</filter-mapping>
三、过滤器的执行过程和生命周期
a、过滤器在应用启动时候就完成了初始化
b、在过滤器范围内的应用每次访问都会调用doFilter方法
c、应用被卸载时会调用destory方法
四、过滤器的几个练习
a、解决POST请求参数中文和输出中文的乱码过滤器
//1、解决POST请求参数中文和输出中文的乱码过滤器
public class SetCharacterEncodingFilter implements Filter {
private FilterConfig filterConfig;
public void destroy() { }
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
String value = filterConfig.getInitParameter("encoding");
if (value == null) {
value = "UTF-8";
}
request.setCharacterEncoding(value);
response.setContentType("text/html;charset=" + value);
chain.doFilter(request, response);// 放行
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
//动态资源不要缓存
public class DynamicResourcesNocacheFilter implements Filter {
@Override
public void destroy() {}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request; // 因为这个方法中的请求和响应是不带协议的所以要强转
HttpServletResponse response;
try {
request = (HttpServletRequest) req;
response = (HttpServletResponse) resp;
} catch (ClassCastException e) {
throw new RuntimeException("不是http协议");
}
response.setHeader("Expires","-1");
response.setHeader("Cache-control", "no-cache");
response.setHeader("Pragma", "no-cache");
chain.doFilter(request, response);
}