springboot 过滤器整合
不讲原理,直接实战吧,哈哈。但是有一点要说一下,拦截器和过滤器的原理是不一样的,这样一定要知道。
下面就看看springboot 整合过滤器
springboot启动
/**
* 启动类
* 东泰 http://dt2008.cn
* 2020-12
*/
@SpringBootApplication
//搜索dao层
@MapperScan("cn.dt2008.mapper")
//扫描过滤器 参数1:controller层位置, 参数2:过滤器地址
@ServletComponentScan(basePackages = {"cn.dt2008.controller", "cn.dt2008.filter"})
public class MySpringBootApplication {
public static void main(String[] arge){
SpringApplication.run(MySpringBootApplication.class, arge);
}
}
Filter过滤器
/**
* 过滤器
* 东泰 http://dt2008.cn
* 2020-11
*/
@WebFilter(urlPatterns = "/apiaaa/v1/*") //过滤的路径
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {
System.out.println("-----------进入过滤器------------");
try {
//放行
filterChain.doFilter(request, response);
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
}
@Override
public void destroy() {
}
}
可以看到 doFilter 方法注释了放行,可以在里面判断是否给予放行和拦截返回返回页面都可以