Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 119 ยท Spring Framework

Spring MVC Without Boot: Java Config, web.xml and WAR Deployment

Build a classic Spring MVC web app without Spring Boot - the dispatcher initializer, WebMvcConfigurer, several view resolvers, @PropertySource values and WAR deployment to Tomcat.

Spring Boot hides the plumbing: it starts an embedded Tomcat, registers the DispatcherServlet and configures dozens of beans. Plenty of real projects don't use it. They deploy a WAR file to a Tomcat or Jetty server that the company already runs, or they maintain an application that started before Boot existed. If you join such a project, AbstractAnnotationConfigDispatcherServletInitializer, @EnableWebMvc and a webapps folder are what you will find.

This lesson shows every piece of that setup: the Maven project, the initializer that replaces web.xml, the Java configuration with view resolvers, property values loaded with @PropertySource, the older web.xml alternative, and how a WAR is deployed and why the context path matters. Spring and Tomcat can't run on this page, so the real files are shown read-only. The two runnable programs model what the container does at startup and how property values resolve. If you are not yet comfortable with the request flow, read Spring MVC first, and Servlet Lifecycle and Deployment for the container side.

The project: a WAR with no web.xml

A WAR (web application archive) is a ZIP file that a servlet container unpacks and runs. The Maven build produces one when the packaging is war:

XML
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>shop</artifactId>          <!-- the WAR is named shop.war -->
    <version>1.0.0</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.release>21</maven.compiler.release>
        <failOnMissingWebXml>false</failOnMissingWebXml>   <!-- no web.xml: the Java initializer replaces it -->
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>             <!-- Tomcat supplies it; never put it in the WAR -->
        </dependency>
    </dependencies>
</project>

Two details cause most first-day problems. The failOnMissingWebXml property tells the WAR plugin that it is fine to have no web.xml (some plugin versions stop the build otherwise, and setting it explicitly is harmless). The servlet API has scope provided, because the container already contains it, and a second copy inside WEB-INF/lib makes class loading fail in confusing ways. The Spring version must match the container: Spring Framework 6 uses the jakarta.servlet packages and needs a Servlet 6.0 container such as Tomcat 10.1, and Spring Framework 7 expects Servlet 6.1 (Tomcat 11). The old javax.servlet packages and Tomcat 9 belong to Spring 5.

The folder layout is the standard Maven one, plus the web resources:

TEXT
shop/
  pom.xml
  src/main/java/com/example/shop/
      config/WebAppInitializer.java      <- replaces web.xml
      config/AppConfig.java              <- root context: services, repositories
      config/WebConfig.java              <- servlet context: controllers, views
      web/ProductController.java
  src/main/resources/app.properties
  src/main/webapp/WEB-INF/views/         <- JSP views (not reachable from the browser)
  src/main/webapp/static/                <- CSS, JavaScript, images

The initializer replaces web.xml

Since Servlet 3.0, a container scans every JAR for a ServletContainerInitializer. Spring ships one (SpringServletContainerInitializer) that finds all your classes implementing WebApplicationInitializer and calls their onStartup method. Extending the convenience base class takes three methods:

Java
package com.example.shop.config;

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {          // the ROOT context (ContextLoaderListener)
        return new Class<?>[] {AppConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {       // the DispatcherServlet's own context (child of root)
        return new Class<?>[] {WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] {"/"};                         // the dispatcher handles every URL
    }

    @Override
    protected Filter[] getServletFilters() {               // filters in front of the dispatcher
        var encoding = new CharacterEncodingFilter("UTF-8", true);
        return new Filter[] {encoding};
    }
}

That is the whole replacement for web.xml. The base class creates two application contexts: the root one for the service layer, and a child one for the web layer (the hierarchy from Beans, Configuration and Component Scanning). The configuration classes are passed as class literals, so a typo is a compile error instead of a surprise at runtime. The program below models what the container and the Spring initializer do when a WAR is dropped in, and how a request URL is split into context path and servlet path. It is plain Java, not Spring or Tomcat.

Java Deploying a WAR: initializers, contexts and the context path

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The same initializer ran for both deployments. The difference is the context path: Tomcat takes it from the WAR file name (shop.war becomes /shop, and the special name ROOT.war becomes /). The servlet path is what is left after removing it. This explains the classic bug of a link <a href="/products"> that works on a developer's laptop (where the app was deployed at the root) and fails on the server (where it lives at /shop). In views, build URLs through the framework: ${pageContext.request.contextPath} in JSP, th:href="@{/products}" in Thymeleaf, or <spring:url value="/products"/>.

The web configuration class

The servlet context's configuration enables Spring MVC and registers your view technology. @EnableWebMvc pulls in DelegatingWebMvcConfiguration, which registers the handler mappings, adapters, message converters and exception resolvers. You customize them by implementing WebMvcConfigurer:

Java
@Configuration
@EnableWebMvc                                   // in a Boot app this would switch Boot's MVC setup off
@ComponentScan("com.example.shop.web")          // finds the @Controller classes
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")                    // URL /shop/static/site.css
                .addResourceLocations("/static/");                   // folder src/main/webapp/static/
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("pages/home");   // a page without controller code
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/views/", ".jsp");                     // the catch-all, so it comes last
    }

    @Bean
    public ThymeleafViewResolver thymeleafViewResolver(SpringTemplateEngine engine) {
        var resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(engine);
        resolver.setViewNames(new String[] {"pages/*"});             // only names starting with pages/
        resolver.setOrder(1);                                        // asked before the JSP resolver
        return resolver;
    }
}

Here two view technologies live side by side: names such as pages/home go to Thymeleaf, and everything else falls through to JSP files below WEB-INF/views/. This only works because of the order and the setViewNames filter, as the earlier lesson showed. The Thymeleaf resolver also needs a SpringTemplateEngine and a SpringResourceTemplateResolver bean, which are plain boilerplate (prefix /WEB-INF/templates/, suffix .html). Files under WEB-INF can't be requested directly by a browser, which is why views live there: only a controller can reach them.

Property values with @PropertySource

Without Boot there is no automatic application.properties. You load files yourself with @PropertySource and read the values with @Value or the Environment:

Java
@Configuration
@ComponentScan("com.example.shop.service")
@PropertySource("classpath:app.properties")
@PropertySource(value = "classpath:app-local.properties", ignoreResourceNotFound = true)   // optional override file
public class AppConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();      // static, so ${...} also works in @Value fields
    }
}

@Service
public class ShopInfo {
    private final String name;
    private final int pageSize;
    private final String[] tags;

    public ShopInfo(@Value("${app.name}") String name,
                    @Value("${page.size:20}") int pageSize,            // 20 if the property is missing
                    @Value("${tags:a,b,c}") String[] tags) {           // a comma-separated list becomes an array
        this.name = name; this.pageSize = pageSize; this.tags = tags;
    }
}

A ${key:default} expression takes the text after the colon when the key is unknown, and @Value("Welcome") without any placeholder is simply a literal. Without a default, a missing property stops the application at startup with Could not resolve placeholder. System properties (-Dserver.port=9090) and environment variables come before your files, and when two files define the same key, the one declared later wins. Placeholders may be nested inside values (app.url=http://${app.host}:${server.port}/shop). The next program resolves values in exactly that order:

Java Property sources, precedence and placeholders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

server.port came from the system property even though the file also defines it, app.host came from the later file, and app.url was assembled from both. Each @Value shape from the code above appears in the second block, including the startup error for a key with no default. Never keep passwords in files inside the WAR: pass them as system properties or environment variables, which win over the files.

If you do need a web.xml

Some servers and older projects still use the XML descriptor. The same setup looks like this in src/main/webapp/WEB-INF/web.xml:

XML
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" version="6.0">

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.example.shop.config.AppConfig</param-value>
    </context-param>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.example.shop.config.WebConfig</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

It says exactly what getRootConfigClasses, getServletConfigClasses and getServletMappings said in Java. If both a web.xml and an initializer exist, both run, so keep only one of them.

Building and deploying

TEXT
mvn clean package            # produces target/shop-1.0.0.war
cp target/shop-1.0.0.war  $CATALINA_HOME/webapps/shop.war     # file name decides the context path
$CATALINA_HOME/bin/startup.sh                                  # or let a running Tomcat hot-deploy it
# open http://localhost:8080/shop/

Set <finalName>shop</finalName> in the <build> section so the file is always called shop.war. Then watch logs/catalina.out (the Tomcat log) for the Spring startup messages. A Spring Boot application can be deployed the same way: make the packaging war, mark spring-boot-starter-tomcat as provided, and extend SpringBootServletInitializer in the main class. For a new project the embedded server is simpler, as Deploying Java Applications explains.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement describes AbstractAnnotationConfigDispatcherServletInitializer correctly?

    The servlet container finds it through the ServletContainerInitializer mechanism, and its three methods name the root configuration, the servlet configuration and the mapping. Component scanning happens in the configuration classes.
  2. 2. A WAR file is named reports.war and is copied into Tomcat's webapps folder. At which URL path does the application run?

    Tomcat derives the context path from the file name. Only ROOT.war is deployed at /.
  3. 3. A JSP view resolver and a Thymeleaf resolver are both configured. Why must the JSP resolver (InternalResourceViewResolver) come last?

    The JSP resolver never says "not mine". Resolvers are tried in order, so the catch-all has to be the last one.
  4. 4. @Value("${page.size:20}") is used and no page.size property exists anywhere. What is injected?

    The text after the colon is the default value. Without it, the missing property would stop the application at startup.
  5. 5. Why is jakarta.servlet-api declared with scope provided in a WAR project?

    Provided scope means that the dependency is needed to compile, but is supplied at runtime by the container.

Summary

  • A WAR is deployed into an existing servlet container. Use packaging war, mark the servlet API provided, and match the Spring version with the Servlet version of the container.
  • AbstractAnnotationConfigDispatcherServletInitializer replaces web.xml: root configuration classes, servlet configuration classes, mappings, and optional filters. The equivalent web.xml uses ContextLoaderListener and DispatcherServlet.
  • @EnableWebMvc plus a WebMvcConfigurer configures resources, view controllers and view resolvers. Several resolvers need explicit orders and the catch-all JSP resolver goes last.
  • @PropertySource loads property files; @Value("${key:default}") injects values. System properties win over files, and a later file wins over an earlier one.
  • The context path comes from the WAR name (ROOT.war means /). Always build URLs with the context path or a URL helper such as @{...}.

Next: Spring MVC: File Upload and Pagination adds the two features that nearly every list-and-form application needs.