1、使用註解
1. 假設Filter類的路徑爲com.sanro.filteride
@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."); } }
2、手動配置url
1. Filter類spa
@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配置類
debug
@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(){...}便可。 }