Getting Started on Undertow Server

  •        0

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.

Undertow is a high performing web server which can be used for both blocking and non-blocking tasks. It is extermely flexible as application can assemble the parts in whatever way it would make sense. It also supports Servlet 4.0, JSR-356 compliant web socket implementation. Undertow is licensed under Apache License, Version 2.0.
Undertow source code is available in github. It can either downloaded and configure the server manually. Other easy option would be directly embedded into the project using the maven dependency as below. Undertow recent version can be checked in github releases page.
It has three components
  1. undertow-core: Undertow core, which provides support for non blocking handlers and web sockets
  2. undertow-servlet: Support for Servlet 3.1
  3. undertow-websockets-jsr: for the Java API for Websockets (JSR-356) standard
Bootstrapping Undertow
Undertow can be started using io.undertow.Undertow builder API. It doesn't have any global container it just assemble the handlers and start the server. Undertow applications has to manage the lifecycle of handlers and resource utitlized by the handlers.
public class HelloWorldServer {

    public static void main(final String[] args) {
        Undertow server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(new HttpHandler() {
                    public void handleRequest(final HttpServerExchange exchange) throws Exception {
                        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
                        StringBuilder output = new StringBuilder("<h1>Checking Status Undertow</h1>");
                        output.append("<h3 style='color:green'>I am up and running at port 8080!!!</h3>");
Undertow server can be instantiated with builder having hostname, port number and handler details. In the HttpHandler, using HttpServerExchange parameter to get the response object. In this case, we are sending status of the server in html format in the response sender.
Undertow bootstrap within milliseconds (log for reference) whereas other microservice frameworks takes seconds to start.
Mar 12, 2019 3:38:10 AM org.xnio.Xnio <clinit>
INFO: XNIO version 3.3.8.Final
Mar 12, 2019 3:38:10 AM org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.3.8.Final
Architecture Overview
An undertow server is basically composed of three things like XNIO Worker Instance, one or more connectors and handler chain to handle the incoming requests.  XNIO Worker is based on the Jboss XNIO project which is simplified low-level I/O layer built on top java nio library. Connectors are tied to XNIO worker with listeners for HTTP/1.1, HTTPS, AJP will generally do all IO operations. After connection, XNIO invokes the HttpOpenListener which creates the server connection(HttpServerConnection) to hold the state associated with the connection. Then, it invokes HttpReadListener which is responsible for parsing the request, they will create HttpServerExchange object populated with request data and then hand it to handler chain.
Root handler chain will be invoked by the connector where built in handlers are available and also custom handler can be created and added.
File Server
Undertow is shipped with many built in handlers like access log handlers, allowed methods, request dumping handler and so on. Resource handler is for listing and finding the files as ftp server. Now we will add the base path for the directory listing using resource manager and it can be handled for exception like file not found.
 HttpHandler handle404Example = new HttpHandler() {
  public void handleRequest(HttpServerExchange exchange) throws Exception {
   exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
   exchange.getResponseSender().send("File Not Found");

 ResourceHandler resourceHandler = new ResourceHandler(
                 new PathResourceManager(Paths.get(System.getProperty("user.home")), 100), handle404Example)
 RequestDumpingHandler requestDumpingHandler = new RequestDumpingHandler(resourceHandler);
 Undertow server = Undertow.builder()
                 .addHttpListener(8080, "localhost")
                 .addPrefixPath("/", requestDumpingHandler)))
Now resourceHandler will list all the files from user home directory, if we try to hit the url with non existing files like http://localhost:8080/test, it will invoke the handle404Example which shows the content like "File not found".

Rest API
We can create rest api for retrieving and presisting the users with routing handler. Routing handler will invoke the handlers based on the api url and methods. In our case, we will route GET method of /users path to retrieve the users and POST method of /users path to save the data. Below example, will have class member holding all the "users", so post is adding and get is retrieving it from the users.
   RoutingHandler routes = new RoutingHandler().get("/users", new HttpHandler() {
           public void handleRequest(HttpServerExchange httpServerExchange) throws Exception {
                 httpServerExchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
       .post("/users", new RequestDumpingHandler(new HttpHandler() {
            public void handleRequest(HttpServerExchange httpServerExchange) throws Exception {
                 FormParserFactory.Builder builder = FormParserFactory.builder();

                 final FormDataParser formDataParser =;

                if (formDataParser != null) {
                     FormData formData = formDataParser.parseBlocking();
                     Integer id = Integer.parseInt(formData.get("id").peek().getValue());
                     User user1 = new User(id, formData.get("name").peek().getValue());
                     httpServerExchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
                     httpServerExchange.getResponseSender().send("added successfully");


  Undertow undertow = Undertow.builder()
                     .addHttpListener(8080, "localhost")
For invoking the POST request, send the data as x-www-form-url-encoded through postman(chrome browser app) with keys as id and name. Likewise the GET request,  http://localhost:8080/users will retrieve the data.

There are more working examples provided as part of undertow project. clone the project and inside the project there is a folder examples. Once the project is build, move to target folder and execute the jar, which shows all the  examples as below.

  $ java -jar undertow-examples.jar
     Welcome to the Undertow Examples
     Please select an example:
     a) Basic Authentication
     b) Chat
     c) File Serving
     d) HTTP2
     e) Hello World
     f) JSR Web Sockets
     g) ModCluster Proxy Server
     h) Reverse Proxy
     i) Server Sent Events
     j) Servlet
    k) Session Handling
    l) Web Socket Extensions
   m) Web Sockets
choose the one and execute to see how that works.



Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter

Related Articles

Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More

Push Notifications using Angular

  • angular push-notifications notifications

Notifications is a message pushed to user's device passively. Browser supports notifications and push API that allows to send message asynchronously to the user. Messages are sent with the help of service workers, it runs as background tasks to receive and relay the messages to the desktop if the application is not opened. It uses web push protocol to register the server and send message to the application. Once user opt-in for the updates, it is effective way of re-engaging users with customized content.

Read More

WebSocket implementation with Spring Boot

  • websocket web-sockets spring-boot java

Spring Boot is a microservice-based Java framework used to create web application. WebSocket API is an advanced technology that provides full-duplex communication channels over a single TCP connection. This article explains about how to implement WebSocket using Spring Boot.

Read More

Build Consulting Website using Next.js

  • react nextjs website-development ssr

One of the popular web framework for building Single page application (SPA) or static site is React library. Application built with React packages will be rendered completely on the client side browser. If you want to reduce the load on client side browser, we need to pre-render the pages in server (Serer side rendering) and serve it to the client. So the client loads the page like simple html page. Also if the pages are rendered from server then search engine will be able to fetch and extract the pages. To do SSR for React, the best abstraction framework is Next.js. In this blog, we will explain how to build a simple consulting website using NextJS.

Read More

Light4j Cookbook - Rest API, CORS and RDBMS

  • light4j sql cors rest-api

Light 4j is a fast, lightweight and cloud-native microservices framework. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like MySQL, also built in option of CORS handler for in-flight request.

Read More

Data dumping through REST API using Spring Batch

  • spring-batch data-dump rest-api java

Most of the cloud services provide API to fetch their data. But data will be given as paginated results as returning the complete data will overshoot the response payload. To discover the complete list of books or e-courses or cloud machine details, we need to call the API page-wise till the end. In this scenario, we can use Spring Batch to get the data page by page and dump it into a file.

Read More

COVID19 Stats using Angular Material Design

  • angular material-design covid covid-stats

Material design is inspired from the real world building architecture language. It is an adaptable system of guidelines, components, and tools that support the best practices of user interface design. Backed by open-source code, Material streamlines collaboration between designers and developers, and helps teams quickly build beautiful products. In this article, we will build COVID stats using Angular Material design.

Read More

Angular Security - Authentication Service

  • angular security authentication jwt

Angular is a framework for creating single page web application. Angular facilitates the security feature and protection mechanism. It provides frameworks by verifying all the routing urls with security authguard interface to validate and verify the user and its permissions.

Read More

RESTEasy Advanced Guide - Filters and Interceptors

  • resteasy rest-api filters interceptors java

RESTEasy is JAX-RS 2.1 compliant framework for developing rest applications. It is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol.

Read More

JWT Authentication using Auth0 Library

  • java jwt authentication security

Json Web Token shortly called as JWT becomes defacto standard for authenticating REST API. In a traditional web application, once the user login credentials are validated, loggedin user object will be stored in session. Till user logs out, session will remain and user can work on the web application without any issues. Rest world is stateless, it is difficult to identify whether the user is already authenticated. One way is to use authenticate every API but that would be too expensive task as the client has to provide credentials in every API. Another approach is to use token.

Read More

ETag Easy With RESTEasy

  • resteasy etag http-header rest-api

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It comprises of frameworks for mock, embeddable server, rest client, proxy servers, logging and so on.In this article, we will walk-through ETag implementation and show the behaviour related to ETag done by rest easy framework. Example is developed using RESTEasy 3.7 and deployed in tomcat as RESTEasy framework is portable.

Read More

Angular Service Workers Usage Guide

  • angular service-worker offline-app

Web developers come across scenarios like web application completely breaks when workstation goes offline. Likewise to get into our application, every time we need to open a browser and then access it. Instead if it is in app, it will be easy to access for end-user. Push notifications similar to email client need to be done through web application. All these are addressed by a magic called service worker.

Read More

Getting Started with Spring Batch

  • spring-batch spring-boot batch-processing

The best way to design a system for handling bulk workloads is to make it a batch system. If we are already using Spring, it will be easy to add a Spring Batch to the project. Spring batch provides a lot of boiler plate features required for batch processing like chunk based processing, transaction management and declarative input/output operations. It also provides job control for start, stop, restart, retry and skip processing also.

Read More

Data Fetching and Form Building using NextJS

  • nextjs data-fetching form-handling

Next.js is one of the easy-to-learn frameworks for server-side pre-render pages for client-side web applications. In this blog, we will see how we can fetch data from API and make it pre-render pages. Also, let's see how forms work in Next.js and collect the data without maintaining the database.

Read More

Getting Started With Django Python Web Framework

  • django python web-framework

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It is pre-loaded with user authentication, content administration, site maps, RSS feeds and many more tasks. Security features provided are cross site scripting (XSS) protection, cross site request forgery protection, SQL injection protection, click-jacking protection, host header validation, session security and so on. It also provides in built caching framework.

Read More

Apache OpenNLP - Document Classification

  • opennlp natural-language-processing nlp document-classification

Apache OpenNLP is a library for natural language processing using machine learning. In this article, we will explore document/text classification by training with sample data and then execute to get its results. We will use plain training model as one example and then training using Navie Bayes Algorithm.

Read More

Connect to MongoDB and Perform CRUD using Java

  • java mongodb database programming

MongoDB is a popular and widely used open source NoSQL database. MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution is quite possible. It is licensed under Server Side Public License. Recently they moved to Server Side Public License, before that MongoDB was released under AGPL. This article will provide basic example to connect and work with MongoDB using Java.

Read More

Laravel Paypal Integration - Smart button with server-side integration

  • laravel paypal smart-button

You would have seen a lot of blogs for paypal php integration with REST api which is driven completely in the backend. For checkout, paypal provides an easy way to checkout for client side ready-to-use smart button payment. This approach will work only from the frontend, which will not be safe and difficult to reconcile as the backend does not have any information about it. Server side integration with the paypal smart button will help us to reconcile or track the payments even after some issues in the users payment journey. In this blog, we have walkthrough the paypal smart button with server side php laravel integration.

Read More

RESTEasy Advanced guide - File Upload

  • resteasy rest-api file-upload java

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the ASL 2.0.

Read More

Cache using Hazelcast InMemory Data Grid

  • hazelcast cache key-value

Hazelcast is an open source In-Memory Data Grid (IMDG). It provides elastically scalable distributed In-Memory computing, widely recognized as the fastest and most scalable approach to application performance.&nbsp;Hazelcast makes distributed computing simple by offering distributed implementations of many developer-friendly interfaces from Java such as Map, Queue, ExecutorService, Lock and JCache.

Read More

We have large collection of open source products. Follow the tags from Tag Cloud >>

Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.