WebApplicationInitializer 인터페이스를 사용하면 web.xml에서 했던 서블릿, 필터, 리스너 설정 등을 java로 설정할 수 있다.
처음에 그것도 모르고 web.xml에 아무것도 없어 당황을....^^;

프로젝트를 하나 만들어 아래와 같이 간단히 등록하고 테스트를 해보니 정상 동작되는 것을 확인했다.

 

package testweb;
 
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
 
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
 
public class Init implements WebApplicationInitializer {
 
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		System.out.println("onStartup...");
		addListender(servletContext);
		addDispatcher(servletContext);
		addFilter(servletContext);
	}
 
	public void addListender(ServletContext servletContext) {
		System.out.println("addListender...");
		AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
		appContext.register(AppConfig.class);
		ContextLoaderListener listender = new ContextLoaderListener(appContext);
		servletContext.addListener(listender);
	}
 
	public void addDispatcher(ServletContext servletContext) {
		System.out.println("addDispatcher...");
		AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
		webContext.register(WebConfig.class);
		DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext);
		ServletRegistration.Dynamic webServlet = servletContext.addServlet("webServlet", dispatcherServlet);
		webServlet.addMapping("/");
		webServlet.setLoadOnStartup(1);
	}
 
	public void addFilter(ServletContext servletContext) {
		System.out.println("addFilter...");
		CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter("UTF-8", true, true);
		FilterRegistration.Dynamic webEncodingFilter = servletContext.addFilter("webEncodingFilter", encodingFilter);
		webEncodingFilter.addMappingForUrlPatterns(null, false, "/*");
	}
}

 

반응형

+ Recent posts