Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Undertow is an extremely lightweight and high-performance web server from JBoss. It supports both blocking and non-blocking APIs with NIO.

Since it’s written is Java, it can be used in any JVM-based applications in embedded mode, even JBoss’s WilfFly server internally uses Undertow to improve the server’s performance.

In this tutorial, we’ll show the features of Undertow and how to use it.

2. Why Undertow?

  • Lightweight: Undertow is extremely lightweight at under 1MB. In embedded mode, it uses only 4MB of heap space at runtime
  • Servlet 3.1: It fully supports Servlet 3.1
  • Web Socket: It supports Web Socket functionality (including JSR-356)
  • Persistent Connection: By default, Undertow includes HTTP persistent connections by adding keep-alive response header. It helps clients that support persistent connections to optimize performance by reusing connection details

3. Using Undertow

Let’s start to use Undertow by creating a simple web server.

3.1. Maven Dependency

To use Undertow, we need to add the following dependency to our pom.xml:

<dependency>
    <groupId>io.undertow</groupId>
    <artifactId>undertow-servlet</artifactId>
    <version>1.4.18.Final</version>
</dependency>

To build a runnable jar, we also need to add maven-shade-plugin. That’s why we also need to add below configuration as well:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
        </execution>
    </executions>
</plugin>

The latest version of Undertow is available in Central Maven Repository.

3.2. Simple Server

With the below code snippet, we can create a simple web server using Undertow’s Builder API:

public class SimpleServer {
    public static void main(String[] args) {
        Undertow server = Undertow.builder().addHttpListener(8080, 
          "localhost").setHandler(exchange -> {
            exchange.getResponseHeaders()
            .put(Headers.CONTENT_TYPE, "text/plain");
          exchange.getResponseSender().send("Hello Baeldung");
        }).build();
        server.start();
    }
}

Here, we’ve used the Builder API to bind 8080 port to this server. Also, note that we have used a lambda expression to use the handler.

We can also use below code snippet to do the same thing without using lambda expressions:

Undertow server = Undertow.builder().addHttpListener(8080, "localhost")
  .setHandler(new HttpHandler() {
      @Override
      public void handleRequest(HttpServerExchange exchange) 
        throws Exception {
          exchange.getResponseHeaders().put(
            Headers.CONTENT_TYPE, "text/plain");
          exchange.getResponseSender().send("Hello Baeldung");
      }
  }).build();

The important thing to note here is the usage of the HttpHandler API. It’s the most important plugin to customize an Undertow application based on our needs.

In this case, we have added a customized handler that would add the Content-Type: text/plain response header with each request.

Similar way, if we want to return some default text with each response, we can use below code snippet:

exchange.getResponseSender()
  .send("Hello Baeldung");

3.3. Secure Access

In most cases, we don’t allow all users to access our server. Usually, users with valid credentials can get access.We can implement the same mechanism with the Undertow.

To implement it, we need to create an identity manager which will check user’s authenticity for every request.

We can use Undertow’s IdentityManager for this:

public class CustomIdentityManager implements IdentityManager {
    private Map<String, char[]> users;

    // standard constructors
    
    @Override
    public Account verify(Account account) {
        return account;
    }
 
    @Override
    public Account verify(Credential credential) {
        return null;
    }
 
    @Override
    public Account verify(String id, Credential credential) {
        Account account = getAccount(id);
        if (account != null && verifyCredential(account, credential)) {
            return account;
        }
        return null;
    }
}

Once the identity manager is created, we need to create a realm which will hold the user credentials:

private static HttpHandler addSecurity(
  HttpHandler toWrap, 
  IdentityManager identityManager) {
 
    HttpHandler handler = toWrap;
    handler = new AuthenticationCallHandler(handler);
    handler = new AuthenticationConstraintHandler(handler);
    List<AuthenticationMechanism> mechanisms = Collections.singletonList(
      new BasicAuthenticationMechanism("Baeldung_Realm"));
    handler = new AuthenticationMechanismsHandler(handler, mechanisms);
    handler = new SecurityInitialHandler(
      AuthenticationMode.PRO_ACTIVE, identityManager, handler);
    return handler;
}

Here, we have used the AuthenticationMode as PRO_ACTIVE which means every request coming to this server will be passed to the defined authentication mechanisms to perform authentication eagerly.

If we define AuthenticationMode as CONSTRAINT_DRIVEN, then only those requests will go through the defined authentication mechanisms where the constraint/s that mandates authentication is triggered.

Now, we just need to map this realm and the identity manager with the server before it starts:

public static void main(String[] args) {
    Map<String, char[]> users = new HashMap<>(2);
    users.put("root", "password".toCharArray());
    users.put("admin", "password".toCharArray());

    IdentityManager idm = new CustomIdentityManager(users);

    Undertow server = Undertow.builder().addHttpListener(8080, "localhost")
      .setHandler(addSecurity(e -> setExchange(e), idm)).build();

    server.start();
}

private static void setExchange(HttpServerExchange exchange) {
    SecurityContext context = exchange.getSecurityContext();
    exchange.getResponseSender().send("Hello " + 
      context.getAuthenticatedAccount().getPrincipal().getName(),
      IoCallback.END_EXCHANGE);
}

Here, we have created two user instances with credentials. Once the server is up, to access it, we need to use any of these two credentials.

3.4. Web Socket

It’s straightforward to create web socket exchange channel with UnderTow’s WebSocketHttpExchange API.

For example, we can open a socket communication channel on path baeldungApp with below code snippet:

public static void main(String[] args) {
    Undertow server = Undertow.builder().addHttpListener(8080, "localhost")
      .setHandler(path().addPrefixPath("/baeldungApp", websocket(
        (exchange, channel) -> {
          channel.getReceiveSetter().set(getListener());
          channel.resumeReceives();
      })).addPrefixPath("/", resource(new ClassPathResourceManager(
        SocketServer.class.getClassLoader(),
        SocketServer.class.getPackage())).addWelcomeFiles("index.html")))
        .build();

    server.start();
}

private static AbstractReceiveListener getListener() {
    return new AbstractReceiveListener() {
        @Override
        protected void onFullTextMessage(WebSocketChannel channel, 
          BufferedTextMessage message) {
            String messageData = message.getData();
            for (WebSocketChannel session : channel.getPeerConnections()) {
                WebSockets.sendText(messageData, session, null);
            }
        }
    };
}

We can create an HTML page named index.html and use JavaScript’s WebSocket API to connect to this channel.

3.5. File Server

With Undertow, we can also create a file server which can display directory content and directly serves files from the directory:

public static void main( String[] args ) {
    Undertow server = Undertow.builder().addHttpListener(8080, "localhost")
        .setHandler(resource(new PathResourceManager(
          Paths.get(System.getProperty("user.home")), 100 ))
        .setDirectoryListingEnabled( true ))
        .build();
    server.start();
}

We don’t need to create any UI content to display the directory contents. Out-of-the-box Undertow provides a page for this display functionality.

4. Spring Boot Plugin

Apart from Tomcat and Jetty, Spring Boot supports UnderTow as the embedded servlet container. To use Undertow, we need to add the following dependency in the pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
    <version>1.5.6.RELEASE</version>
</dependency>

The latest version of Spring Boot Undertow plugin is available in Central Maven Repository.

5. Conclusion

In this article, we learned about Undertow and how we can create different types of servers with it.

Like always, the full source code is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.