Spring boot之过滤器(Filter)

2020-09-25  本文已影响0人  黑曼巴yk

前言

通过Filter过滤器进行拦截。

@Slf4j
@Component
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("myFilter init....");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setAttribute("name", "dankun");
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("myFilter doFilter....");
    }

    @Override
    public void destroy() {
        System.out.println("myFilter destroy....");
    }
}

Filter注册

@Configuration
public class WebConfig {
    @Autowired
    private MyFilter myFilter;

    @Bean
    public FilterRegistrationBean initFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(myFilter);
        registrationBean.setName("myFilter");
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }
}

Filter init生命周期

init在程序启动时候执行一次。比如读取全局的 appContext

  private ApplicationContext appContext;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext());
    }

注解形式

也可以通过 注解形式配置,而不用通过Config 声明

@WebFilter(filterName = "urlRedirectFilter", urlPatterns = "/*")

在程序启动时候,加上@ServletComponentScan注解

@ServletComponentScan
public class Application {

    public static void main(String[] args) {
        PandoraBootstrap.run(args);
        SpringApplication.run(Application.class, args);
    }
}
上一篇下一篇

猜你喜欢

热点阅读