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

    一、使用注解
    1. 假设Filter类的路径为com.sanro.filter

    @Slf4j
    @WebFilter(filterName = "authFilter", urlPatterns = "/*")
    @Order(1) //测试好像这个参数不生效,实际生效的是Filter扫描到的顺序(所以起名很重要)
    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");
            }
        }
    }

    2. 自动扫描配置如下

    @Slf4j
    @EnableScheduling
    @ServletComponentScan(basePackages = {"com.sanro.filter"}) //这一句完成了配置,Springboot的”懒理念“真的厉害。
    @SpringBootApplication
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
            log.debug("rest server start success.");
        }
    }

    二、手动配置

    1. Filter类

    @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");
            }
        }
    }

    2. Filter配置类

    @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(){...}即可。
    }
  • 相关阅读:
    网站添加微信支付功能(小白填坑)
    spring项目中如何添加定时器以及在定时器中自动生成sprng注入对象
    当时间一天天流逝,一个三十岁的屌丝程序员留下了了什么?
    解决使用canvas生成含有微信头像的邀请海报没有微信头像
    jQuery v1.10.2如何判断checkbox(复选框)是否被选中
    调用钉钉接口发送消息
    .net core ajax使用EPPlus上传excle导入总结
    Java企业级权限管理系统的开发总结
    RESTful学习小结
    JS实战(京东秒杀)
  • 原文地址:https://www.cnblogs.com/yoyotl/p/10853499.html
Copyright © 2011-2022 走看看