Filter 简介
filter称为过滤器,可以对web 服务器管理的所有资源: Jsp, Servlet,静态图片文件或静态html文件等进行拦截,从而实现一些特殊的功能。例如实现URL级别的权限访问控制,过滤敏感词汇,压缩响应信息等高级功能。
public class LogCostFilter implements Filter {
public abstract void init(FilterConfig paramFilterConfig) throws ServletException;
public abstract void doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse, FilterChain
paramFilterChain) throws IOException, ServletException;
public abstract void destroy();
}
工作原理
doFilter方法中,配置对哪个web 资源进行拦截后,WEB服务器每次在调用web资源service方法之前,都会先调用一下filter的doFilter方法,因此,在该方法内编写代码可以达到此目的:
- 调用目标资源之前,让一段代码执行
- 是否调用目标资源(即是否让用户访问web 资源)
- 调用目标资源之后,让一段代码执行(filterChian)
Demo
LogCostFilter
public class LogCostFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("---Filter初始化---");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("UTF-8");
servletResponse.setContentType("text/html;charset=UTF-8");
long start = System.currentTimeMillis();
System.out.println("---调用service之前执行的一段代码---");
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("Execute cost="+(System.currentTimeMillis()-start));
}
@Override
public void destroy() {
System.out.println("---Filter销毁---");
}
}
FilterConfig
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean registFilter() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new LogCostFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setName("LogCostFilter");
registrationBean.setOrder(1);
return registrationBean;
}
}
过滤字符串标准代码
public class CharacterEncodingFilter extends OncePerRequestFilter{
private static final boolean responseSetCharacterEncodingAvailable = ClassUtils.hasMethod(
HttpServletResponse.class, "setCharacterEncoding", new Class[] { String.class });
// 需要设置的编码方式,为了支持可配置,Spring把编码方式设置成了一个变量
private String encoding;
// 是否强制使用统一编码,也是为了支持可配置
private boolean forceEncoding;
// 构造器,在这里,Spring把forceEncoding的值默认设置成了false
public CharacterEncodingFilter(){
this.forceEncoding = false;
}
// encoding/forceEncoding的setter方法
public void setEncoding(String encoding){
this.encoding = encoding;
}
public void setForceEncoding(boolean forceEncoding){
this.forceEncoding = forceEncoding;
}
// Spring通过GenericFilterBean抽象类,对Filter接口进行了整合,
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException{
if ((this.encoding != null) && (((this.forceEncoding) || (request.getCharacterEncoding() == null)))) {
request.setCharacterEncoding(this.encoding);
if ((this.forceEncoding) && (responseSetCharacterEncodingAvailable)) {
response.setCharacterEncoding(this.encoding);
}
}
filterChain.doFilter(request, response);
}
}
网友评论