A very simple embedded Java web server with Undertow. Head over to http://undertow.io/ to learn more about Undertow. This example is the same as shown on the homepage just written slightly differently. Undertow is the web server of choice for StubbornJava. It has a very clean and easy to follow API and has a fairly low learning curve. Every request and or filter is a HttpHandler. HttpHandlers can do filtering, routing, validation, exception handling and much more all with the same simple interface. Since the web server is embedded we can easily run this example insaide of any IDE or as a standalone executable Jar. No application containers in sight. Whew!
Java Hello World Web Server
A simple and lightweight Java HTTP server.
/*
* Creating HttpHandlers as a method and passing it as a method reference is pretty clean.
* This also helps reduce accidentally adding state to handlers.
*/
public static void helloWorldHandler(HttpServerExchange exchange) {
exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send("Hello World!");
}
public static void main(String[] args) {
int port = 8080;
/*
* "localhost" will ONLY listen on local host.
* If you want the server reachable from the outside you need to set "0.0.0.0"
*/
String host = "localhost";
/*
* This web server has a single handler with no routing.
* ALL urls are handled by the helloWorldHandler.
*/
Undertow server = Undertow.builder()
// Add the helloWorldHandler as a method reference.
.addHttpListener(port, host, HelloWorldServer::helloWorldHandler)
.build();
logger.debug("starting on http://" + host + ":" + port);
server.start();
}
Output
curl -X GET localhost:8080
Hello World!
curl -X GET localhost:8080/123
Hello World!
Notice how all urls respond the same. Interested in Routing with Undertow?