Replacing web.xml with Java config

Posted by {"name"=>"Palash Ray", "email"=>"paawak@gmail.com", "url"=>"https://www.linkedin.com/in/palash-ray/"} on April 07, 2016 · 1 min read

Post Servlet 3.0, web.xml has become redundant. It can now be replaced with pure Java configuration.
We can do that even without Spring. But since we are using Spring MVC, I am taking the Spring example. Define a class implementing the WebApplicationInitializer, as below:

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebappInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext container) {
	// Create the dispatcher servlet's Spring application context
	AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
	dispatcherContext.register(WebConfig.class);
	// Register and map the dispatcher servlet
	ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
	dispatcher.setLoadOnStartup(1);
	dispatcher.addMapping("/");
    }
}

Note that we can define servlets, filters, etc., whatever we do in the web.xml. Its super simple and very readable.
Please be aware that you need to include the below servlet 3.x dependency in your pom.xml:

		
			javax.servlet
			javax.servlet-api
			3.1.0
			provided
		

Moreover, you have to include the below Maven plugin and set the failOnMissingWebXml property to false in pom.xml:

		
			
				maven-war-plugin
				2.4
				
					false
				
			
...

 
The sources will be found here:
https://github.com/paawak/blog/tree/master/code/simple-spring-rest