ember.js 在Java HTTP服务器的响应中发送文件

7xllpg7q  于 2023-01-30  发布在  Java
关注(0)|答案(1)|浏览(188)

我使用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();
    } 
}

但是,不幸的是,我在尝试加载主页时遇到以下错误。
"未捕获的语法错误:意外标记〈"
使用Node.js处理相同的Ember应用程序时工作正常。我想我没有正确发送HTTP响应。任何帮助都是感激的。

hyrbngr7

hyrbngr71#

也许你的文件路径有问题。还要注意readFileToString已经过时了。
这是一个工作的服务器,它会将您的index.html发送到前端。

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class myServer {
    public static void main(String[] args) throws Exception {
        System.out.println("server ...");
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/", new HHandler());
        //server.createContext("/getbookarray", new HHandler());
        //server.setExecutor(null); // creates a default executor
        server.start();
        //server.getExecutor();
    }

    static class HHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange t) throws IOException {
            Headers h = t.getResponseHeaders();


            String line;
            String resp = "";

            try {
                File newFile = new File("src/index.html");
                System.out.println("*****lecture du fichier*****");
                System.out.println("nom du fichier: " + newFile.getName());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(newFile)));

                while ((line = bufferedReader.readLine()) != null) {
                    System.out.println(line);
                    resp += line;
                }
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            h.add("Content-Type", "application/json");
            t.sendResponseHeaders(200, resp.length());
            OutputStream os = t.getResponseBody();
            os.write(resp.getBytes());
            os.close();
        }
    }
}

你可以使用轻量级服务器nanoHttpd,用下面的代码你也可以把你的index.html文件发送到你的前端。

import fi.iki.elonen.NanoHTTPD;

import java.io.*;

public class App extends NanoHTTPD {

    public App() throws IOException {
        super(8080);
        start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
        System.out.println("\nRunning! Point your browsers to http://localhost:8080/ \n");
    }

    public static void main(String[] args) {
        try {
            new App();
        } catch (IOException ioe) {
            System.err.println("Couldn't start server:\n" + ioe);
        }
    }

    @Override
    public Response serve(NanoHTTPD.IHTTPSession session) {

        File newFile = new File("src/index.html");
        System.out.println("*****lecture du fichier*****");
        System.out.println("nom du fichier: " + newFile.getName());

        String line;
        String reponse = "";

        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(newFile)));
            while ((line = bufferedReader.readLine()) != null){
                reponse += line;
            }
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return newFixedLengthResponse(reponse);
    }
}

相关问题