SpringBoot在初始化filter之前加载加载部分bean

@Configuration
public class LoginFilter implements Filter {
	private RedisConfig redisConfig;
	
	/**
     * 封装,不需要过滤的list列表
     */
	private static final List PATTERNS = new ArrayList();
    
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
		PATTERNS.add(Pattern.compile("/user/login.html"));
		PATTERNS.add(Pattern.compile(".*[(\\.js)||(\\.css)||(\\.png)||(\\.jpg)]"));
		
		ServletContext servletContext = filterConfig.getServletContext();
	    ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
	    redisConfig = (RedisConfig) ctx.getBean("redisConfig");// 装配Bean
        }

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");

		if (isInclude(path)) {
			chain.doFilter(request, response);
			return;
		}
		RedisUtil redisUtil = redisConfig.redisUtil();
		Object object = redisUtil.get("loginUserInfo");
		if (object == null) {
			response.sendRedirect(request.getContextPath() + "/user/login.html");
			System.out.println("这里是需要处理的url进入的方法");
			return;
		} else {
			chain.doFilter(request, response);
		}
		
	}

	@Override
	public void destroy() {
		System.out.println("destroy");
	}
	
    /**
     * 是否需要过滤
     * @param url
     * @return
     */
    private boolean isInclude(String url) {
        for (Pattern pattern : PATTERNS) {
            Matcher matcher = pattern.matcher(url);
            if (matcher.matches()) {
                return true;
            }
        }
        return false;
    }


}


你可能感兴趣的:(SpringBoot在初始化filter之前加载加载部分bean)