gpt4 book ai didi

java - Java内置的Web Server如何指向index.html?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:05:46 25 4
gpt4 key购买 nike

我有一个非常简单的 Java Web 服务器(在 this tutorial 之后),有没有办法在处理程序中指向 index.html 文件(来自 Bootstrap)而不是对响应进行硬编码?

import java.io.*;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.*;

public class SO {
public static void main(String[] args) throws Exception {
int port = 9000;
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
System.out.println("server started at " + port);
server.createContext("/", new RootHandler());
server.setExecutor(null);
server.start();
}

public static class RootHandler implements HttpHandler {

@Override
public void handle(HttpExchange he) throws IOException {
String response = "<h1>Static Response</h1>";
he.sendResponseHeaders(200, response.length());
OutputStream os = he.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}

最佳答案

内置的 HttpServer 非常低级,据我所知,不提供此功能。但是没有什么能阻止您读取文件并将其内容发送到响应输出流:

File file = new File("index.html");
he.sendResponseHeaders(200, file.length());
try (OutputStream os = he.getResponseBody()) {
Files.copy(file.toPath(), os);
}

关于java - Java内置的Web Server如何指向index.html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37765072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com