What is the role of the web.xml file or Java Config in setting up Spring MVC?

web.xml and Java-based configuration are the two ways to bootstrap a Spring MVC application inside a servlet container, both ultimately responsible for registering DispatcherServlet and wiring up the application context.

Key Points: • In web.xml, DispatcherServlet is declared as a <servlet> with a <servlet-mapping> defining which URL patterns it handles. • web.xml can also register ContextLoaderListener to build the root application context alongside the servlet's own context. • Java Config replaces web.xml with a class extending AbstractAnnotationConfigDispatcherServletInitializer, which programmatically registers the same servlet and listener behavior. • Java Config is the modern, preferred approach — it's type-safe, refactorable, and avoids XML entirely, and is what Spring Boot builds on internally. • Regardless of which is used, the end result is the same: DispatcherServlet is registered and ready to route requests to controllers.

Example: A legacy application might declare DispatcherServlet in web.xml with a servlet-mapping of "/", while a modern equivalent extends AbstractAnnotationConfigDispatcherServletInitializer and overrides getServletMappings() to return the same "/" pattern, achieving identical behavior without any XML file.

Code Example:

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    protected Class<?>[] getRootConfigClasses() { return new Class<?>[]{ RootConfig.class }; }
    protected Class<?>[] getServletConfigClasses() { return new Class<?>[]{ WebConfig.class }; }
    protected String[] getServletMappings() { return new String[]{ "/" }; }
}

Interview Tip: A concise interview answer is:

"Both web.xml and Java Config exist to register DispatcherServlet and set up the application context that powers Spring MVC. web.xml does it declaratively with XML, while Java Config does the same thing programmatically by extending AbstractAnnotationConfigDispatcherServletInitializer — which is the approach I prefer, and what Spring Boot uses under the hood."