mardi 25 février 2020

Java http server does not load resources(js, css, images)

I created a simple HTTP server. I have this index.html:

<html>
<head>
    <title>My Site</title>
    <link rel="stylesheet" type="text/css" href="../static/css/simple.css"/>
</head>
<body>

<h2>Hello world</h2>
<p>Image:</p>

<img src="../static/images/someimage.jpg" alt="W3Schools.com" width="400" height="400">
</body>
</html>

And a simple handler:

public class MainHandler implements HttpHandler {

    public void handle(HttpExchange exchange) throws IOException {

        InputStream resourceAsStream = getClass().getResourceAsStream("/templates/index.html");
        InputStreamReader isReader = new InputStreamReader(resourceAsStream);
        BufferedReader reader = new BufferedReader(isReader);

        StringBuilder sb = new StringBuilder();
        String str;
        while ((str = reader.readLine()) != null) {
            sb.append(str);
        }

        String response = sb.toString();

        exchange.sendResponseHeaders(200, sb.length());
        OutputStream os = exchange.getResponseBody();
        os.write(response.getBytes());
        os.close();
    }
}

When I open index.html - CSS and image do not load.

I added the project to the Github repository: simple-server and hope somebody can help with this problem.




Aucun commentaire:

Enregistrer un commentaire