如何使用Java内置Web服务器指向index.html?

时间:2016-06-11 14:52:10

标签: java webserver

我有一个非常简单的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();
        }
    }
}

1 个答案:

答案 0 :(得分:4)

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

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