import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetSocketAddress; public class main { private static HttpServer server; private static int port = 8080; public static void main(String[] args) throws Exception { server = HttpServer.create(new InetSocketAddress(port), 0); createHttpContext("/", new MainContext()); server.setExecutor(null); // creates a default executor server.start(); System.out.println("HTTP server started (listening on port " + port + "!)"); } private static void createHttpContext(String path, HttpHandler handler) { server.createContext(path, new SafeHttpHandler(handler)); } public static class SafeHttpHandler implements HttpHandler { private HttpHandler handler; public SafeHttpHandler(HttpHandler handler) { this.handler = handler; } public void handle(HttpExchange exchange) throws IOException { System.out.println("[web server] Handling request: " + exchange.getRequestURI()); try { handler.handle(exchange); } catch (Throwable e) { String stackTrace = getStackTrace(e); sendServerError(exchange, stackTrace); System.out.println(stackTrace); } finally { exchange.close(); System.out.println("[web server] Done handling request: " + exchange.getRequestURI()); } } } public static String getStackTrace(Throwable e) { StringWriter stringWriter = new StringWriter(); e.printStackTrace(new PrintWriter(stringWriter)); return stringWriter.toString(); } public static void sendHtml(HttpExchange exchange, String content) throws IOException { int responseCode = 200; String contentType = "text/html"; sendHttpTextResponse(exchange, responseCode, content, contentType); } public static void sendHttpTextResponse(HttpExchange exchange, int responseCode, String content, String contentType) throws IOException { byte[] bytes = content.getBytes("UTF-8"); String header = contentType + "; charset=utf-8"; System.out.println("Sending content type: " + header); exchange.getResponseHeaders().set("Content-Type", header); exchange.sendResponseHeaders(responseCode, bytes.length); OutputStream os = exchange.getResponseBody(); os.write(bytes); os.close(); } public static void sendServerError(HttpExchange exchange, String response) throws IOException { sendHttpTextResponse(exchange, 500, response, "text/plain"); } public static class MainContext implements HttpHandler { public void handle(HttpExchange httpExchange) throws IOException { sendHtml(httpExchange, "Hello world! JavaX."); } } }