springboot集成过滤器
封装自定义接口filter
包含两个方法,第一个过滤的路径数组,第二个为过滤器执行的顺序.spring boot 会按照order值的大小,从小到大的顺序来依次过滤。
package com.theeternity.common.baseFilter;
import javax.servlet.Filter;
/**
* @program: ApiBoot
* @description: 封装Filter
* @author: TheEternity Zhang
* @create: 2019-02-17 13:08
*/
public interface MappingFilter extends Filter {
String[] addUrlPatterns();
int order();
}
书写具体的filter
package com.theeternity.beans.filterConfig;
import com.theeternity.common.baseFilter.MappingFilter;
import javax.servlet.*;
import javax.servlet.FilterConfig;
import java.io.IOException;
/**
* @program: ApiBoot
* @description: 权限过滤器
* @author: TheEternity Zhang
* @create: 2019-02-17 13:14
*/
public class AuthFilter implements MappingFilter {
@Override
public String[] addUrlPatterns() {
return new String[]{"/*"};
}
@Override
public int order() {
return 0;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//具体逻辑
}
@Override
public void destroy() {
}
}
注入bean到容器
package com.theeternity.beans.filterConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @program: ApiBoot
* @description: 注册过滤器
* @author: TheEternity Zhang
* @create: 2019-02-17 13:10
*/
@Configuration
public class FilterConfig {
private Logger logger= LoggerFactory.getLogger(FilterConfig.class);
@Bean
public FilterRegistrationBean registFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
AuthFilter authFilter=new AuthFilter();
registration.setFilter(authFilter);
registration.addUrlPatterns(authFilter.addUrlPatterns());
registration.setOrder(authFilter.order());
registration.setName("AuthFilter");
return registration;
}
}