Servlet container initialization through code

In this section, you will learn about Servlet container initialization through code in Spring MVC.

Servlet container initialization through code

Servlet container initialization through code

In this section, you will learn about Servlet container initialization through code in Spring MVC.

You can configure the Servlet container programmatically in a Servlet 3.0+ environment. You can use it as an alternative or in combination with a web.xml.

Given below sample code for registering a DispatcherServlet :

import org.springframework.web.WebApplicationInitializer;

public class ApplicationInitializer implements WebApplicationInitializer {
	@Override
	public void onStartup(ServletContext container) {
		XmlWebApplicationContext ctxt = new XmlWebApplicationContext();
		ctxt.setConfigLocation("/WEB-INF/spring-config/dispatcher-config.xml");
		
		ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(ctxt));
		registration.setLoadOnStartup(1);
		registration.addMapping("/");
	}
}

In Spring MVC, WebApplicationInitializer interface automatically initialize Servlet 3 container with your provided configuration.

Registering DispatcherServlet becomes much easier using AbstractDispatcherServletInitializer by overriding the functions which used to assign DispatcherServlet configuration location and the Servlet mapping.

Given below Java-based Spring configuration :

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
	return null;
	}
	
	@Override
	protected Class<?>[] getServletConfigClasses() {
	return new Class[] { AppConfig.class };
	}
	
	@Override
	protected String[] getServletMappings() {
	return new String[] { "/" };
	}

}

Using AbstractDispatcherServletInitializer, the above configuration can also be done by using  XML-based Spring configuration as shown below :

public class AppInitializer extends AbstractDispatcherServletInitializer {
	
	@Override
	protected WebApplicationContext createRootApplicationContext() {
		return null;
	}
	
	@Override
	protected WebApplicationContext createServletApplicationContext() {
		XmlWebApplicationContext appContext = new XmlWebApplicationContext();
		appContext.setConfigLocation("/WEB-INF/spring-config/dispatcher-config.xml");
		return appContext;
	}
	
	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}

}

AbstractDispatcherServletInitializer also provide suitable and appropriate way to add Filters, which automatically mapped to the DispatcherServlet :

public class AppInitializer extends AbstractDispatcherServletInitializer {

	// ...
	
	@Override
	protected Filter[] getServletFilters() {
	return new Filter[] { new HiddenHttpMethodFilter(), new CharacterEncodingFilter() };
	}

}