ZetCode

Spring DefaultServlet tutorial

last modified October 18, 2023

Spring DefaultServlet tutorial shows how to enable default servlet in a Spring application.

Spring is a popular Java application framework. In the tutorial, we use Spring 5 version.

DefaultServlet

DefaultServlet is a default resource-serving servlet for most web applications, used to serve static resources such as HTML pages and images.

DefaultServletHttpRequestHandler attempts to auto-detect the default Servlet for the containers, such as Tomcat, Jetty, Wildfly, and Resin, at startup time. If the default Servlet has been custom configured with a different name then the default Servlet's name must be explicitly provided.

If we rewrite the DefaultServlet's route (/), we can enable it with DefaultServletHandlerConfigurer's enable method so that we can still serve static resoruces with the container's default servlet.

Spring DefaultServlet example

In the following application we configure the Spring dispatcher servlet to the / path, which rewrites the default servlet's one. We enable the default servlet with DefaultServletHandlerConfigurer.

The application serves a simple HTML home page, which is a static resource.

pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           └───config
│   │                   MyWebInitializer.java
│   │                   WebConfig.java
│   ├───resources
│   │       logback.xml
│   └───webapp
│           index.html
└───test
    └───java

This is the project structure.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>defaultservletex</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.4.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.23</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.3.2</version>
            </plugin>

        </plugins>
    </build>

</project>

This is the Maven build file. We have the following dependencies: javax.servlet-api for Java Servlet technology, logback-classic for logging, and spring-webmvc for creating Spring Web MVC applications.

The maven-war-plugin creates web archives (WAR).

com/zetcode/config/MyWebInitializer.java
package com.zetcode.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MyWebInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

MyWebInitializer initializes a Spring web application.

@Override
protected String[] getServletMappings() {
    return new String[]{"/"};
}

We register the Spring DispatcherServlet to the / path. This replaces the DefaultServlet; therefore we have to register a default servlet handler in the configuration file.

com/zetcode/config/WebConfig.java
package com.zetcode.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

WebConfig enables Spring MVC with @EnableWebMvc and configures the DefaultServlet with DefaultServletHandlerConfigurer's enable method.

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

The configureDefaultServletHandling configures a DefaultServletHttpRequestHandler with a URL mapping of /** and the lowest priority relative to other URL mappings. This way the static resource requests are handled by the container's default Servlet.

webapp/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home page</title>
</head>
<body>

<p>
    This is home page.
</p>

</body>
</html>

This is the home page. It is a static resource and is automatically served by the DefaultServlet.

$ curl localhost:8080
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home page</title>
</head>
<body>

<p>
    This is home page.
</p>

</body>
</html>    

When we run the application, the home page is served.

In this article we shown how to register a default servlet in a Spring application.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Spring tutorials.