filter

In Spring, we can use FilterChainProxy to manage custom filters properly.

Custom resource xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="webFilterChain" class="org.springframework.security.web.DefaultSecurityFilterChain">
        <constructor-arg name="requestMatcher">
            <bean class="org.springframework.security.web.util.matcher.NegatedRequestMatcher">
                <constructor-arg name="requestMatcher">
                    <bean class="org.springframework.security.web.util.matcher.RegexRequestMatcher">
                        <constructor-arg name="httpMethod" value=""/>
                        <constructor-arg name="pattern" value="/api/.*"/>
                    </bean>
                </constructor-arg>
            </bean>
        </constructor-arg>
        <constructor-arg name="filters">
            <list>
                <bean class="org.springframework.security.web.csrf.CsrfFilter">
                    <constructor-arg name="csrfTokenRepository">
                        <bean class="org.springframework.security.web.csrf.CookieCsrfTokenRepository"/>
                    </constructor-arg>
                </bean>
                <ref bean="springSessionRepositoryFilter"/>
            </list>
        </constructor-arg>
    </bean>

    <bean id="customFilterChainProxy" class="org.springframework.security.web.FilterChainProxy">
        <constructor-arg>
            <list>
                <ref bean="webFilterChain"/>
            </list>
        </constructor-arg>
    </bean>

</beans>

web.xml filter configuration

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            <!-- ... -->
            classpath:spring/filter.xml
        </param-value>
    </context-param>

 <!-- Custom Filter -->
    <filter>
        <filter-name>customFilterChainProxy</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>customFilterChainProxy</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Explain

customFilterChainProxy filter-name in web.xml. This tells Container(Tomcat) to add filter by Class org.springframework.web.filter.DelegatingFilterProxy.

DelegatingFilterProxy : Spring will search filter-name (customFilterChainProxy) in Spring context for Good Management.And customFilterChainProxy is initialized in filter.xml resource file.