2016-06-11 2 views
2

매우 간단한 Java 웹 서버 (this tutorial)가 있는데, 응답을 하드 코딩하는 대신 처리기에서 (부트 스트랩에서 오는) index.html 파일을 가리키는 방법이 있습니까?Java 내장 웹 서버를 사용하여 index.html을 가리키는 방법은 무엇입니까?

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

재미있는 사실은 : 문제가 아닌 어떤 포인터가 – mjn

+0

: 자바가 없기 때문에 index.html을 가리키는 것은 가능하지 않고, 아무것도 파일을 읽고 응답 출력 스트림에 컨텐츠를 전송하지 못하도록 없다 명확한. 응답 본문으로 로컬 index.html 파일의 내용을 제공 하시겠습니까? – mjn

+0

정확히, 응답 본문으로 index.html의 내용을 표시하고 싶습니다. – Ninius86

답변

4

내장 된 HttpServer는 매우 낮은 수준이며 AFAIK는이 기능을 제공하지 않습니다.

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