过滤器
拦截器
对比
过滤器Filter
过滤器基于servlet
fileter类
public class LogCostFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { long start = System.currentTimeMillis(); //这是过程链 filterChain.doFilter(servletRequest,servletResponse); System.out.println("Filter1: Execute cost="+(System.currentTimeMillis()-start)); } @Override public void destroy() { } }
配置方式
通过文件配置方式
@Configurationpublic class FilterConfig { @Bean public FilterRegistrationBean registFilter() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new LogCostFilter()); registration.addUrlPatterns("/*"); registration.setName("LogCostFilter"); registration.setOrder(1); return registration; } }
通过注释方式
//在过滤器类上面添加注释@WebFilter(urlPatterns = "/*", filterName = "logFilter2")public class LogCostFilter2 implements Filter {//在主类上添加@ServletComponentScan("com.liu.spring_boot_mybatis.filter")//注意最后不要加.*这里就是扫描包public class App {
结果
启动项目 刷新网页
控制台输出
拦截器Intercepter
Intercepter类
public class LogCostInterceptor implements HandlerInterceptor { long start = System.currentTimeMillis(); @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { start = System.currentTimeMillis(); return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("Interceptor cost="+(System.currentTimeMillis()-start)); } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
代码说明
preHandle是请求执行前执行的,postHandler是请求结束执行的,但只有preHandle方法返回true的时候才会执行,afterCompletion是视图渲染完成后才执行,同样需要preHandle返回true,该方法通常用于清理资源等工作。
配置方式
@Configurationpublic class InterceptorConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LogCostInterceptor()).addPathPatterns("/**"); super.addInterceptors(registry); } }
作者:cccccttttyyy
链接:https://www.jianshu.com/p/7c126f00a749