zoukankan      html  css  js  c++  java
  • springboot配置Filter的两种方法

    一 使用注解

    @Slf4j
    @WebFilter(filterName = "authFilter", urlPatterns = "/*")
    @Order(1) //顺序
    public class AuthFilter implements Filter {
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            log.debug("start to auth request validate...111");
            HttpServletRequest req = (HttpServletRequest) request;
            String token = req.getHeader("token");
            if (token != null) {
            //    :TODO check token
                log.info("auth success");
                chain.doFilter(request, response);
            } else {
                log.err("auth failed");
            }
        }
    }
    @Slf4j
    @EnableScheduling
    @ServletComponentScan(basePackages = {"com.sanro.filter"}) //这一句就完成了配置
    @SpringBootApplication
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
            log.debug("rest server start success.");
        }
    }

    二 手动配置

    @Slf4j
    @Component
    public class AuthFilter implements Filter {
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            log.debug("start to auth request validate...111");
            HttpServletRequest req = (HttpServletRequest) request;
            String token = req.getHeader("token");
            if (token != null) {
            //    :TODO check token
                log.info("auth success");
                chain.doFilter(request, response);
            } else {
                log.err("auth failed");
            }
        }
    }
    @Configuration
    public class FilterConfig {
    
        @Autowired
        private AuthFilter authFilter;
    
        @Bean
        public FilterRegistrationBean registerAuthFilter() {
            FilterRegistrationBean registration = new FilterRegistrationBean();
            registration.setFilter(authFilter);
            registration.addUrlPatterns("/*");
            registration.setName("authFilter");//手动注册进去
            registration.setOrder(1);  //值越小,Filter越靠前。
            return registration;
        }
        
        //如果有多个Filter,再写一个public FilterRegistrationBean registerOtherFilter(){...}即可。
    }
  • 相关阅读:
    老调重弹之整除与实数除
    #define 预处理指令(C++,C#,VB.NET)
    char类型和string类型(C++,C#)
    使用XPATH对XML数据进行解析
    SQL Server查询优化之:使用提示(Hints)
    XSLT几种应用场景
    在C++中定义常量的两种方法的比较
    为SSIS编写自定义任务项(Task)之高级篇
    利用反射绑定事件处理程序(C#)
    自定义打开Reflector的方式
  • 原文地址:https://www.cnblogs.com/ydymz/p/14225889.html
Copyright © 2011-2022 走看看