前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springboot配置Filter的两种方法

springboot配置Filter的两种方法

作者头像
ydymz
发布2021-01-05 14:53:46
1.6K0
发布2021-01-05 14:53:46
举报
文章被收录于专栏:lgp20151222

一 使用注解

代码语言:javascript
复制
@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");
        }
    }
}
代码语言:javascript
复制
@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.");
    }
}

二 手动配置

代码语言:javascript
复制
@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");
        }
    }
}
代码语言:javascript
复制
@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(){...}即可。
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-01-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档