配置类,注入过滤器UserFilter
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean<?> configFilter(){
FilterRegistrationBean<UserFilter> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setFilter(new UserFilter());
//过滤掉全部请求
filterRegistrationBean.addUrlPatterns("/*");
//排除不需要过滤的请求
Set<String> stringSet = new HashSet<>();
stringSet.add("/api/user/login");
String urls = StringUtils.join(stringSet.toArray(),",");
filterRegistrationBean.addInitParameter("exclusions",urls);
return filterRegistrationBean;
}
}
UserFilter过滤器
public class UserFilter implements Filter {
public static final String PARAM_NAME_EXCLUSIONS = "exclusions";
public static final String SEPARATOR = ",";
private Set<String> excludesUrls;
private UserTokenService userTokenService;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//过滤器注入service,原因:过滤器执行的时候,service还没有被实例化注入
ServletContext sc = filterConfig.getServletContext();
WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(sc);
if(cxt != null) {
if (userTokenService == null) {
userTokenService = cxt.getBean(UserTokenService.class);
}
}
String param = filterConfig.getInitParameter(PARAM_NAME_EXCLUSIONS);
if (param != null && param.trim().length() != 0) {
this.excludesUrls = new HashSet<>(Arrays.asList(param.split(SEPARATOR)));
}
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
String requestURI = httpRequest.getRequestURI();
if (!this.excludesUrls.contains(requestURI)) {
String ticket = servletRequest.getParameter("ticket");
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
log.info("UserFilter开始销毁");
}
}