Spring Boot2 学习笔记之集成 Filter(六)
java 中的 filter 类似于 php 和 node 中的中间件 middleware,叫法不同但用法类似
Spring Boot
会自动扫描所有的FilterRegistrationBean
类型的Bean
,然后,将它们返回的 Filter 自动注册到 Servlet 容器中,无需任何配置。
创建一个名为 filter 的 package,里面创建一个 class 文件AuthFilterRegistrationBean.class
@Slf4j @Order(10) @Component public class AuthFilterRegistrationBean extends FilterRegistrationBean<Filter> { @Override public Filter getFilter() { return new AuthFilter(); } //针对部分 url 生效 @PostConstruct public void init() { setFilter(new AuthFilter()); List<String> urls = new ArrayList<>(); urls.add("/"); urls.add("/user/*"); urls.add("/api/*"); urls.add("/get_headers"); setUrlPatterns(urls); } class AuthFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { log.info("doFilter:check authentication"); HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; String url = req.getRequestURI(); String token = req.getHeader("token"); log.info("url:{}",url); log.info("token:{}",token); if(token == null){ res.sendError(500); }else{ chain.doFilter(request,response); } } } }