Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring 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:


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:


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 -> {
            .put(Headers.CONTENT_TYPE, "text/plain");
          exchange.getResponseSender().send("Hello Baeldung");

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() {
      public void handleRequest(HttpServerExchange exchange) 
        throws Exception {
            Headers.CONTENT_TYPE, "text/plain");
          exchange.getResponseSender().send("Hello Baeldung");

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:

  .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
    public Account verify(Account account) {
        return account;
    public Account verify(Credential credential) {
        return null;
    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();


private static void setExchange(HttpServerExchange exchange) {
    SecurityContext context = exchange.getSecurityContext();
    exchange.getResponseSender().send("Hello " + 

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) -> {
      })).addPrefixPath("/", resource(new ClassPathResourceManager(


private static AbstractReceiveListener getListener() {
    return new AbstractReceiveListener() {
        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 ))

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:


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:

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.