springboot过滤器实例

首先,要了解一下什么是过滤器,什么情况下用过滤器。看了好多资料,最让人理解的就是过滤器是主要针对servlet的,而拦截器主要用在spring框架最为合适。

下面就上案例:

首先,你需要实现Filter

public class TokenFilter implements Filter {
    private static Logger logger = Logger.getLogger(TokenFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("1.初始化过滤器");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("2.请求过滤");

        HttpServletRequest req = (HttpServletRequest)servletRequest;
        servletResponse.setCharacterEncoding("UTF-8");
        servletResponse.setContentType("application/json; charset=utf-8");
        String token = req.getHeader("token");
        
        //todo:业务逻辑
    }

    @Override
    public void destroy() {
        logger.info("3.过滤器被销毁");
    }
}

接着,配置FilterConfig

@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean registFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new TokenFilter());
        registration.addUrlPatterns("/*");
        registration.setName("TokenFilter");
        registration.setOrder(1);
        return registration;
    }

}

一定要在你的Application上加上@ComponentScan配置

@ComponentScan(basePackages= {你的包})

最后,在你启动你的项目的时候Filter就会自动初始化,并在你请求的根据你的要求进行过滤。

 

 

你可能感兴趣的:(springboot)