SpringBoot之过滤器配置和应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pengyangyan/article/details/83144975

一、创建过滤器

单独创建一个filter的类继承Filter接口,重写接口里面的init()、doFilter()、destory()方法即可。

public class LoginFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(LoginFilter.class);


    private FilterConfig config;

    @Override
    public void init(FilterConfig filterConfig) {
        this.config =filterConfig;
        logger.info("--------------------init----------------------");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("--------------------doFilter----------------------");
        ServletContext context = this.config.getServletContext();
        long before = System.currentTimeMillis();
        context.log("开始过滤...");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        context.log("Filter已经拦截用户请求地址:"+httpServletRequest.getServletPath());
        filterChain.doFilter(servletRequest, servletResponse);
        //---------下面代码用于对服务器响应执行后处理---------
        long after = System.currentTimeMillis();
        //记录日志
        context.log("过滤结束");
        //再次记录日志
        context.log("请求被定位到" + httpServletRequest.getRequestURI() + "所花的时间为: " + (after - before));
    }

    @Override
    public void destroy() {
        this.config = null;
        logger.info("--------------------destroy----------------------");
    }
}

二、配置过滤器

配置过滤器有两种方法:1、通过在上面创建的类上添加注解的方式进行配置;2、通过在springboot的启动类中通过@bean进行注解配置。我主要使用的是第一种。第一种在配置完后需要在启动类添加@ServletComponentScan注解使springboot帮助我们找到配置好的过滤器

@Order(1)  //过滤器优先级
@WebFilter(urlPatterns = "/*",filterName = "LoginFilter")
public class LoginFilter implements Filter {
}

@SpringBootApplication
@ServletComponentScan  //注解让SpringBoot帮助我们扫到Filter
public class PkApplication {

    public static void main(String[] args) {
        SpringApplication.run(PkApplication.class, args);
    }
}

三、结束语

现在运行springboot就可通过日志打印观察到过滤器的生命周期,需要通过过滤器完成相应需求的小伙伴们,将方法写到过滤器的doFilter()方法中即可。

猜你喜欢

转载自blog.csdn.net/pengyangyan/article/details/83144975