web.xml 의 Filter 부분을 동적으로 처리해야 할 일이 생겼다.
Spring 3.1 이상을 사용하게 되면 org.springframework.web.WebApplicationInitializer 를 이용하게되면 더 심플하겠지만 현재 상황에서는 Spring 2.5 환경이여서 불가능!!
Servlet 3.x (javax.servlet.ServletContainerInitializer) 만으로 처리해보자.
유의할 점은 Tomcat 8.x 에서는 아래와 같이 그대로 해도 정상적으로 작동하지만 JBoss와 같이 Java EE 환경에서는
jar cvf webxml.jar META-INF/services/javax.servlet.ServletContainerInitializer pe.kr.ddakker.WebXml.class
와 같이 jar 생성 후 WEB-INF/lib 하위에 위치 시켜야 정상 작동합니다.
build.gradle
dependencies { providedCompile 'javax.servlet:javax.servlet-api:3.1.0' }
WebXml.java
package pe.kr.ddakker; import java.util.EnumSet; import java.util.Set; import javax.servlet.DispatcherType; import javax.servlet.FilterRegistration; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.ServletException; import pe.kr.ddakker.filter.TestFilter; public class WebXml implements ServletContainerInitializer { @Override public void onStartup(Set> c, ServletContext servletContext) throws ServletException { System.out.println("ServletContainerInitializer"); TestFilter testFilter = new TestFilter(); FilterRegistration.Dynamic test = servletContext.addFilter("testFilter", testFilter); test.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*"); } }
TestFilter.java
package pe.kr.ddakker.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class TestFilter implements Filter { public TestFilter() { } public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // pass the request along the filter chain System.out.println("TestFilter S"); chain.doFilter(request, response); System.out.println("TestFilter E"); } public void init(FilterConfig fConfig) throws ServletException { } }
classpath 하위 META-INF/services/javax.servlet.ServletContainerInitializer
pe.kr.ddakker.WebXml