Saturday, September 11, 2021

Smallest Java hello world web application

  • Requires no dependencies other the Java runtime itself. 
  • Since JDK 11+, you can run the file directly
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpServer;
public class WebApp {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(9394), 0);
server.createContext("/ping").setHandler(h -> {
final String response = "pong!";
h.sendResponseHeaders(200, response.getBytes().length);
try (OutputStream os = h.getResponseBody()) {
os.write(response.getBytes());
}
});
server.createContext("/shutdown").setHandler(h -> server.stop(0));
server.start();
}
}
view raw WebApp.java hosted with ❤ by GitHub