有多少人一提到 Java 只知道 Spring 的 ?
一说到开发 JavaWeb 就是 SSM, SSI 啥的,其实 JDK8 里自带一个轻量的 WebServer,不需要任何依赖,
偶尔想写一点纯粹的 api 数据接口的时候还是有用的
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class TinyServer {
public static void main(String[] args) throws IOException {
int port = 8000;
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/", (exchange) -> {
String responseText = "Hello World!";
exchange.sendResponseHeaders(200, response.length());
try (OutputStream os = exchange.getResponseBody()) {
os.write(responseText.getBytes());
}
});
server.start();
System.out.println("server listen on port " + port);
}
}