0

私はsun.net.HttpServerを使用して独自の小さなWebサーバーを実装しています... cssとjavascriptを有効にするために、HttpHandlerを使用してコードを書きましたが、jsディレクトリには2つのファイルがあります... 1つのファイルに対して機能しますが、2つのファイルを転送する場合...エラーが発生しました。お気に入り

java.io.IOException: ヘッダーは既に送信されています

これを修正する方法...これがコーディングです

class DirectoryServicesForJS implements HttpHandler {

    @Override
    public void handle(HttpExchange http) throws IOException {
        // HTTP METHOD (GET, POST, DELETE, PUT)
        System.out.println("Java script transfered...");
        List<String> jsFiles = new ArrayList<String>();
        ;
        Files.walk(Paths.get("web/js")).forEach(filePath -> {
            if (Files.isRegularFile(filePath)) {
                jsFiles.add(filePath.toString());
            }
        });
        for (String filePath : jsFiles) {
            try {
                StringBuilder code = new StringBuilder();
                try {
                    BufferedReader in = new BufferedReader(new FileReader(
                            filePath));
                    String str;
                    while ((str = in.readLine()) != null) {
                        code.append(str);
                    }
                    in.close();

                } catch (IOException e) {
                    System.out.println();
                }
                String response = code.toString();
                http.sendResponseHeaders(200, response.length()); // error line
                System.out.println(filePath);
                http.setAttribute("Content-Type", "text/javascript");
                OutputStream os = http.getResponseBody();
                os.write(response.getBytes());
                os.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
4

1 に答える 1

0

すべてのcssとjsを転送するには、次のようにコードを書くことができます...

        server = HttpServer.create(new InetSocketAddress(port), backlog);
        server.createContext("/", new IndexPage());
        List<String> cssFiles = new ArrayList<String>();
        Files.walk(Paths.get("web/css")).forEach(filePath -> {
            if (Files.isRegularFile(filePath)) {
                cssFiles.add(filePath.getFileName().toString());
            }
        });
        for (String cssFile : cssFiles) {
            server.createContext("/css/" + cssFile,
                    new DirectoryServicesForCSS(cssFile));
        }
        List<String> jsFiles = new ArrayList<String>();
        Files.walk(Paths.get("web/js")).forEach(filePath -> {
            if (Files.isRegularFile(filePath)) {
                jsFiles.add(filePath.getFileName().toString());
            }
        });
        for (String jsFile : jsFiles) {
            server.createContext("/js/" + jsFile,
                    new DirectoryServicesForJS(jsFile));
        }
        // server.setExecutor(Executors.newCachedThreadPool());
        server.setExecutor(null);
        server.start();

そして、次のように HttpHandler コードを書く必要があります...

    class DirectoryServicesForCSS implements HttpHandler {

    private String style;

    public DirectoryServicesForCSS(String style) {
        this.style = style;
    }

    @Override
    public void handle(HttpExchange http) throws IOException {
        // HTTP METHOD (GET, POST, DELETE, PUT)
        if (http.getRequestMethod().equals("GET")) {
            System.out.println("cascade style sheet transfered..." + style);
            try {
                StringBuilder contentBuilder = new StringBuilder();
                try {
                    BufferedReader in = new BufferedReader(new FileReader(
                            "web/css/" + style));
                    String str;
                    while ((str = in.readLine()) != null) {
                        contentBuilder.append(str);
                    }
                    in.close();
                } catch (IOException e) {
                }
                String response = contentBuilder.toString();
                http.sendResponseHeaders(200, response.length());
                OutputStream os = http.getResponseBody();
                os.write(response.getBytes());
                os.flush();
                os.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

     class DirectoryServicesForJS implements HttpHandler {

    private String script;

    public DirectoryServicesForJS(String script) {
        this.script = script;
    }

    @Override
    public void handle(HttpExchange http) throws IOException {
        // HTTP METHOD (GET, POST, DELETE, PUT)
        if (http.getRequestMethod().equals("GET")) {
            System.out.println("Java scripts transfered..." + script);
            try {

                StringBuilder code = new StringBuilder();
                try {
                    BufferedReader in = new BufferedReader(new FileReader(
                            "web/js/" + script));
                    String str;
                    while ((str = in.readLine()) != null) {
                        code.append(str);
                    }
                    in.close();

                } catch (IOException e) {
                    System.out.println();
                }
                String response = code.toString();
                http.sendResponseHeaders(200, response.length());
                http.setAttribute("Content-Type", "text/javascript");
                OutputStream os = http.getResponseBody();
                os.write(response.getBytes());
                os.flush();
                os.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

たとえば、HTMLページで利用できることを確認してください..

<html>
<head>
    <title>Shopping Portal</title>
    <link href="css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body class="container-fluid">
<div class="alert alert-success alert-dismissable">
    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
    <strong>Successfully!</strong> You are new user.
</div>
    <h1 class="text-primary">Welcome to Shopping Portal</h1>
    <hr/>
    <p>Content will be updated later</p>
</body>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</html>
于 2015-03-05T12:12:52.963 に答える