Spring Boot配置Filter有两种方式。下面分别来介绍。
重写3个方法。初始化init,执行doFilter,销毁destroy。
public class MyFilter1 implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
filterChain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
Spring Boot官网是这么介绍@ServletComponentScan:
Scanning for Servlets, Filters, and listeners
When using an embedded container, automatic registration of @WebServlet, @WebFilter, and @WebListener annotated classes can be enabled using @ServletComponentScan
翻译成中文:
Scanning for Servlets, Filters, and listeners
When using an embedded container, automatic registration of @WebServlet, @WebFilter, and @WebListener annotated classes can be enabled using @ServletComponentScan
在自定义MyFilter1类上使用注解@WebFilter,这样就配置好了。
属性 | 类型 | 是否必需 | 说明 |
---|---|---|---|
asyncSupported | boolean | 否 | 指定Filter是否支持异步模式 |
dispatcherTypes | DispatcherType[] | 否 | 指定Filter对哪种方式的请求进行过滤。 支持的属性:ASYNC、ERROR、FORWARD、INCLUDE、REQUEST; 默认过滤所有方式的请求 |
filterName | String | 否 | Filter名称 |
initParams | WebInitParam[] | 否 | 配置参数 |
displayName | String | 否 | Filter显示名 |
servletNames | String[] | 否 | 指定对哪些Servlet进行过滤 |
urlPatterns/value | String[] | 否 | 两个属性作用相同,指定拦截的路径 |
我们可以使用filterName指定过滤器的名字。使用value指定过滤的规则。
使用配置类注册自定义的Filter.不使用注解@WebFilter
使用注解@Configuration
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(myfilter());
//配置过滤规则
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName", "paramValue");
//设置过滤器名字
registration.setName("myfilter");
registration.setOrder(2);
return registration;
}
@Bean(name = "myfilter")
public Filter myfilter() {
return new MyFilter1();
}
}
至此方式二也完成了。
在方式一中可以在自定义Filter的类上添加注解@Order。值为整形,越小优先级越高。
在方式二中可以在注册自定义Filter中设置,使用setOrder()方法。
在自定义的Filter类中。定义一个set集合,元素为不必过滤的url。然后在doFilter中判断。代码如下
public class TokenFilter implements Filter {
private static final Set ALLOWED_PATHS = Collections
.unmodifiableSet(new HashSet<>(Arrays.asList("/user/getServerRSAPublicKey", "/user/registerForLawyer",
"/user/login", "/user/getVerificationCode", "/user/wechatLogin")));
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
boolean allowedPath = ALLOWED_PATHS.contains(path);
if (allowedPath) {
filterChain.doFilter(req, res);
} else {
//添加需过滤的url的逻辑
filterChain.doFilter(request, res);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}