If you’re working with Spring, check out "REST With Spring":


1. Introduction

This article will provide an overview of how to register a servlet within Java EE and Spring Boot. Specifically, we will look at two ways to register a Java Servlet in Java EE — one using a web.xml file, and the other using annotations. Then we’ll register servlets in Spring Boot using XML configuration, Java configuration, and through configurable properties.

A great introductory article on servlets can be found here.

2. Registering Servlets in Java EE

Let’s go over two ways to register a servlet in Java EE. First, we can register a servlet via web.xml. Alternatively, we can use the Java EE @WebServlet annotation.

2.1. Via web.xml

The most common way to register a servlet within your Java EE application is to add it to your web.xml file:


As you can see, this involves two steps: (1) adding our servlet to the servlet tag, making sure to also specify the source path to the class the servlet resides within, and (2) specifying the URL path the servlet will be exposed on in the url-pattern tag.

The Java EE web.xml file is usually found in WebContent/WEB-INF.

2.2. Via Annotations

Now let’s register our servlet using the @WebServlet annotation on our custom servlet class. This eliminates the need for servlet mappings in the server.xml and registration of the servlet in web.xml:

  name = "AnnotationExample",
  description = "Example Servlet Using Annotations",
  urlPatterns = {"/AnnotationExample"}
public class Example extends HttpServlet {	
    protected void doGet(
      HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("<p>Hello World!</p>");

The code above demonstrates how to add that annotation directly to a servlet. The servlet will still be available at the same URL path as before.

3. Registering Servlets in Spring Boot

Now that we’ve shown how to register servlets in Java EE, let’s take a look at several ways to register servlets in a Spring Boot application.

3.1. Programmatic Registration

Spring Boot supports 100% programmatic configuration of a web application.

First, we’ll implement the WebApplicationInitializer interface while also using a subclass of WebMvcConfigurerAdapter, which allows you to override preset defaults instead of having to specify each particular configuration setting, saving you time and allowing you to work with several tried and true settings out-of-the-box.

Let’s look at a sample WebApplicationInitializer implementation:

public class WebAppInitializer implements WebApplicationInitializer {
    public void onStartup(ServletContext container) throws ServletException {
        AnnotationConfigWebApplicationContext ctx
          = new AnnotationConfigWebApplicationContext();

        ServletRegistration.Dynamic servlet = container.addServlet(
          "dispatcherExample", new DispatcherServlet(ctx));

Next, let’s extend the WebMvcConfigurerAdapter class:

public class WebMvcConfigure extends WebMvcConfigurerAdapter {

    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver
          = new InternalResourceViewResolver();
        return resolver;

    public void configureDefaultServletHandling(
      DefaultServletHandlerConfigurer configurer) {

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
          .resourceChain(true).addResolver(new PathResourceResolver());

Above we specify some of the default settings for JSP servlets explicitly in order to support .jsp views and static resource serving.

3.2. XML Configuration

Another way to configure and register servlets within Spring Boot is through web.xml:



The web.xml used to specify configuration in Spring is similar to that found in Java EE. Above, you can see how we specify a few more parameters via attributes under the servlet tag.

Here we use another XML to complete the configuration:

<beans ...>
    <context:component-scan base-package="com.baeldung"/>

        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>

Remember that your Spring web.xml will usually live in src/main/webapp/WEB-INF.

3.3. Combining XML and Programmatic Registration

Let’s mix an XML configuration approach with Spring’s programmatic configuration:

public void onStartup(ServletContext container) throws ServletException {
   XmlWebApplicationContext xctx = new XmlWebApplicationContext();

   ServletRegistration.Dynamic servlet = container.addServlet(
     "dispatcher", new DispatcherServlet(ctx));

Let’s also configure the dispatcher servlet:

<beans ...>

    <context:component-scan base-package="com.baeldung"/>
    <bean class="com.baeldung.configuration.WebAppInitializer"/>

3.4. Registration by Bean

We can also programmatically configure and register our servlets using a ServletRegistrationBean. Below we’ll do so in order to register an HttpServlet (which implements the javax.servlet.Servlet interface):

public ServletRegistrationBean exampleServletBean() {
    ServletRegistrationBean bean = new ServletRegistrationBean(
      new CustomServlet(), "/exampleServlet/*");
    return bean;

The main advantage of this approach is that it enables you to add both multiple servlets as well as different kinds of servlets to your Spring application.

Instead of merely utilizing a DispatcherServlet, which is a more specific kind of HttpServlet and the most common kind used in the WebApplicationInitializer programmatic approach to configuration we explored in section 3.1, we’ll use a simpler HttpServlet subclass instance which exposes the four basic HttpRequest operations through four functions: doGet(), doPost(), doPut(), and doDelete() just like in Java EE.

Remember that HttpServlet is an abstract class (so it can’t be instantiated). We can whip up a custom extension easily, though:

public class CustomServlet extends HttpServlet{

4. Registering Servlets with Properties

Another, though uncommon, way to configure and register your servlets is to use a custom properties file loaded into the app via a PropertyLoader, PropertySource, or PropertySources instance object.

This provides an intermediate kind of configuration and the ability to otherwise customize application.properties which provide little direct configuration for non-embedded servlets.

4.1. System Properties Approach

We can add some custom settings to our application.properties file or another properties file. Let’s add a few settings to configure our DispatcherServlet:


Let’s load our custom properties into our application:

System.setProperty("custom.config.location", "classpath:custom.properties");

And now we can access those properties via:


4.2. Custom Properties Approach

Let’s start with a custom.properties file:


We can then use a run-of-the-mill Property Loader:

public Properties getProperties(String file) throws IOException {
  Properties prop = new Properties();
  InputStream input = null;
  input = getClass().getResourceAsStream(file);
  if (input != null) {
  return prop;

And now we can add these custom properties as constants to our WebApplicationInitializer implementation:

private static final PropertyLoader pl = new PropertyLoader(); 
private static final Properties springProps
  = pl.getProperties("custom_spring.properties"); 

public static final String SERVLET_NAME
  = springProps.getProperty("servlet.name"); 
public static final String SERVLET_MAPPING
  = springProps.getProperty("servlet.mapping");

We can then use them to, for example, configure our dispatcher servlet:

ServletRegistration.Dynamic servlet = container.addServlet(
  SERVLET_NAME, new DispatcherServlet(ctx));

The advantage of this approach is the absence of .xml maintenance but with easy-to-modify configuration settings that don’t require redeploying the codebase.

4.3. The PropertySource Approach

A faster way to accomplish the above is to make use of Spring’s PropertySource which allows a configuration file to be accessed and loaded.

PropertyResolver is an interface implemented by ConfigurableEnvironment, which makes application properties available at servlet startup and initialization:

public class ExampleCustomConfig { 
    ConfigurableEnvironment env; 

    public String getProperty(String key) { 
        return env.getProperty(key); 

Above, we autowire a dependency into the class and specify the location of our custom properties file. We can then fetch our salient property by calling the function getProperty() passing in the String value.

4.4. The PropertySource Programmatic Approach

We can combine the above approach (which involves fetching property values) with the approach below (which allows us to programmatically specify those values):

ConfigurableEnvironment env = new StandardEnvironment(); 
MutablePropertySources props = env.getPropertySources(); 
Map map = new HashMap(); map.put("key", "value"); 
props.addFirst(new MapPropertySource("Map", map));

We’ve created a map linking a key to a value then add that map to PropertySources enabling invocation as needed.

5. Registering Embedded Servlets

Lastly, we’ll also take a look at basic configuration and registration of embedded servlets within Spring Boot.

An embedded servlet provides full web container (Tomcat, Jetty, etc.) functionality without having to install or maintain the web-container separately.

You can add the required dependencies and configuration for simple live server deployment wherever such functionality is supported painlessly, compactly, and quickly.

We’ll only look at how to do this Tomcat but the same approach can be undertaken for Jetty and alternatives.

Let’s specify the dependency for an embedded Tomcat 8 web container in pom.xml:


Now let’s add the tags required to successfully add Tomcat to the .war produced by Maven at build-time:


If you are using Spring Boot, you can instead add Spring’s spring-boot-starter-tomcat dependency to your pom.xml:


5.1. Registration Through Properties

Spring Boot supports configuring most possible Spring settings through application.properties. After adding the necessary embedded servlet dependencies to your pom.xml, you can customize and configure your embedded servlet using several such configuration options:


Above are some of the application settings that can be used to configure the DispatcherServlet and static resource sharing. Settings for embedded servlets, SSL support, and sessions are also available.

There are really too many configuration parameters to list here but you can see the full list in the Spring Boot documentation.

5.2. Configuration Through YAML

Similarly, we can configure our embedded servlet container using YAML. This requires the use of a specialized YAML property loader — the YamlPropertySourceLoader  — which exposes our YAML and makes the keys and values therein available for use within our app.

YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
PropertySource<?> yamlProps = sourceLoader.load("yamlProps", resource, null);

5.3. Programmatic Configuration Through TomcatEmbeddedServletContainerFactory

Programmatic configuration of an embedded servlet container is possible through a subclassed instance of EmbeddedServletContainerFactory. For example, you can use the TomcatEmbeddedServletContainerFactory to configure your embedded Tomcat servlet.

The TomcatEmbeddedServletContainerFactory wraps the org.apache.catalina.startup.Tomcat object providing additional configuration options:

public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory tomcatContainerFactory
      = new TomcatEmbeddedServletContainerFactory();
    return tomcatContainerFactory;

Then we can configure the returned instance:


Each of those particular settings can be made configurable using any of the methods previously described.

We can also directly access and manipulate the org.apache.catalina.startup.Tomcat object:

Tomcat tomcat = new Tomcat();

6. Conclusion

In this article, we’ve reviewed several ways to register a Servlet in a Java EE and Spring Boot application.

The source code used in this tutorial is available in the Github project.

The new Certification Class of "REST With Spring" is finally out: