使用Java写一个简易web服务器来替代nginx功能。
main:
public static void main(String[] args) {
ServerConfigLoader serverConfigLoader = Factory.serverConfigLoader();
ServerConfig serverConfig = serverConfigLoader.getServerConfig();
HttpServer httpServer = SimpleFileServer.createFileServer(new InetSocketAddress(Integer.parseInt(serverConfig.serverPort())),
Path.of(serverConfig.contextLocation()), SimpleFileServer.OutputLevel.VERBOSE);
httpServer.start();
}
config:
public class ServerConfigLoader {
private ServerConfig serverConfig;
public ServerConfigLoader() {
String configFileName = "server.properties";
try (InputStream input = ServerConfigLoader.class.getClassLoader().getResourceAsStream(configFileName)) {
Properties prop = new Properties();
prop.load(input);
this.serverConfig = new ServerConfig(prop.getProperty("server.port"), prop.getProperty("context.location"));
} catch (IOException ex) {
System.out.println("Start web server failed: " + ex.getLocalizedMessage());
ex.printStackTrace();
}
}
public ServerConfig getServerConfig() {
return serverConfig;
}
}
public record ServerConfig(String serverPort, String contextLocation) {
}
public class Factory {
public static ServerConfigLoader serverConfigLoader() {
return new ServerConfigLoader();
}
}
到此,极简web server就写完了。
配置文件:
server.properties
server.port=8080
context.location=D:\\your-dictionary
标签:web,Java,ServerConfig,server,ServerConfigLoader,服务器,serverConfig,public
From: https://www.cnblogs.com/jiayuan2006/p/17839433.html