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 {
private static final Logger log = LogManager.getLogger(ClientFilter.class);
private static String value = "";
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
value = filterConfig.getInitParameter("value");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
log.debug("start to auth request validate...111");
log.info(value);
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");
}
}
}
filter 中无法直接获取 properties 配置文件中的值,可以通过 Filter 配置类传入
2.Filter 配置类
@Configuration
public class FilterConfig {
@Value("${value}")
private String value;
@Bean
public FilterRegistrationBean registerAuthFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(authFilter);
registration.addUrlPatterns("/*");
registration.setName("authFilter");
registration.setOrder(1); //值越小,Filter越靠前。
// 传入参数
Map<String, String> initParameters = new HashMap<String, String>();
initParameters.put("value", value);
registration.setInitParameters(initParameters);
return registration;
}
//如果有多个Filter,再写一个public FilterRegistrationBean registerOtherFilter(){...}即可。
}
版权声明
作者: 一沙世界
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于