tomcat容器初始化顺序监听器–>过滤器–>servlet,因此springMVCservlet初始化之前,过滤器就已经初始化过了,如果在过滤器中需要注入spring容器管理的bean是注入不进去的,因此需要在spring监听器中初始化需要注入的bean,才能在过滤器中注入,而且过滤器的定义需要使用spring定义的DelegatingFilterProxy来实现,web.xml部分代码如下

<filter>
        <filter-name>testFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>testFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

其余部分只需要在spring容器中加载testFilter就行了,例子testFilter如下:
注意此处的filter必须为实现javax.Filter的类,而且初始化需要放在spring监听器中,即必须在过滤器初始化之前初始化

@Component
public class TestFilter implements Filter
{
    private static final Logger logger = LogManager.getLogger(TestFilter.class);

    @Autowired
    private UserService userService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws ServletException, IOException
    {
        logger.info(JSONArray.fromObject(userService.list()));
        filterChain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig)
        throws ServletException
    {
        logger.info("初始化filter");
    }

    @Override
    public void destroy()
    {
        logger.info("destroyfilter");
    }
}

如果要保留Filter原有的init,destroy方法的调用,还需要配置初始化参数targetFilterLifecycle为true,该参数默认为false,代码例子如下:

<filter>
        <filter-name>testFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>testFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐