我正在使用Ember作为前端和Java作为后端。当输入localhost:8080时,需要显示Ember主页index.html。以前,我使用Node.js,并且下面的代码行起到了作用
res.sendfile('./public/index.html');
现在我正在转向Java,但是我无法达到相同的结果。我尝试了以下代码。
public static void main(String[] args) throws Exception
{
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/", new HHandler());
server.createContext("/getbookarray", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class HHandler implements HttpHandler
{
@Override
public void handle(HttpExchange t) throws IOException
{
File file = new File("..\\public\\index.html");
String response = FileUtils.readFileToString(file);
String encoding = "UTF-8";
t.getResponseHeaders().set("Content-Type", "text/html; charset=" + encoding);
t.getResponseHeaders().set("Accept-Ranges", "bytes");
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes("UTF-8"));
os.close();
}
}
但是,不幸的是在尝试加载主页时我收到了以下错误信息。
"未捕获的 SyntaxError: 意外的令牌 <"
当使用 Node.js 处理相同的 Ember 应用程序时正常工作。我猜测我没有正确地发送 HTTP 响应。任何帮助将不胜感激。
os.close()
之前尝试使用os.flush()
,看看是否有所不同。 - undefined