自学内容网 自学内容网

springboot WebFilter+@Component urlPatterns 全部拦截

问题描述
@WebFilter(filterName = “ssoFilter”,urlPatterns = “/*”)配置

@Order中的value越小,优先级越高。
解决方法一:
在springboot启动类上添加
@ServletComponentScan(basePackages = “com.package.path”)

解决方法二:
手动配置bean(推荐这种方式,可以在FilterRegistrationBean里设置Order)不需要@WebFilter注解

package com.zhkj.saas.ims.lnterceptor;

import com.zhkj.saas.ims.controller.ProxyController;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author lvyuanjun
 * @date 2023/4/26 15:27
 */
public class ChannelFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            ServletRequest requestWrapper = null;
            if (request instanceof HttpServletRequest) {
                HttpServletRequest req = (HttpServletRequest) request;
                String requestURI = req.getRequestURI();
                boolean state = ProxyController.REQUEST_URI_DATA_AUTH_LIST.contains(requestURI);
                if(state){
                    requestWrapper = new RequestParameterWrapper(req);
                }
            }
            if (requestWrapper == null) {
                chain.doFilter(request, response);
            } else {
                chain.doFilter(requestWrapper, response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {

    }
}

@Configuration
public class WebAuthFilterConfig {
 
    @Bean
    public FilterRegistrationBean webAuthFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(loginFilter());
        registration.setName("ChannelFilter");
        registration.addUrlPatterns("/spu/*");
        registration.setOrder(0);
        return registration;
    }
 
    @Bean
    public Filter channelFilter() {
        return new ChannelFilter();
    }
}

尝试了如下几种情况:

  1. Filter 实现类 + @WebFilter + @ServletComponentScan:正常urlpattern的Filter
  2. Filter 实现类 + FilterRegistrationBean构造 + @Configuration:正常urlpattern的Filter,并且可以设置Order
  3. 仅仅 Filter实现类 + @Component :会注册一个urlpattern 为 /*的过滤器
  4. 通过1、2、3可以得知,只要在Filter实现类上增加 @Component ,就会导致 1个正常urlpattern的filter+1个拦截/*的filter(由于@Component注解导致)

原文地址:https://blog.csdn.net/lvyuanj/article/details/137955454

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!