Java - HttpServer not serving images

1.1k views Asked by At

I have a simple setup including a HttpServer with some context to load image and CSS files:

public class Server {
    private HttpServer httpServer;

    public Server(int port, String path, HttpHandler handler) {
        try {
            httpServer = HttpServer.create(new InetSocketAddress(port), 0);

            httpServer.createContext(path, handler);

            // load css files
            List<String> cssFiles = new ArrayList<String>();
            Files.walk(Paths.get("../css")).forEach(filePath -> {
                if (Files.isRegularFile(filePath)) {
                    cssFiles.add(filePath.getFileName().toString());
                }
            });
            for (String cssFile : cssFiles) {
                httpServer.createContext("/css/" + cssFile, new CssHandler(cssFile));
            }

            // load image files
            List<String> imgFiles = new ArrayList<String>();
            Files.walk(Paths.get("../images")).forEach(filePath -> {
                if (Files.isRegularFile(filePath)) {
                    imgFiles.add(filePath.getFileName().toString());
                }
            });
            for (String imgFile : imgFiles) {
                httpServer.createContext("/images/" + imgFile, new ImageHandler(imgFile));
            }

            httpServer.setExecutor(null);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void start() {
        this.httpServer.start();
    }
}

In addition to that there is a css handler which works perfectly fine and and an image handler class, which serves images defined in html tags, BUT images which are included via css tag "background-image" cannot be loaded.. why?

ImageHandler:

class ImageHandler implements HttpHandler {
    private String img;

    public ImageHandler(String img) {
        this.img = img;
    }

    @Override
    public void handle(HttpExchange http) throws IOException {
        if (http.getRequestMethod().equals("GET")) {
            System.out.println("img transfered..." + img);
            try {
                StringBuilder contentBuilder = new StringBuilder();
                try {
                    BufferedReader in = new BufferedReader(new FileReader("../images/" + img));
                    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();
            }
        }
    }
}

Sooo,

this works:

<img src="images/example.png"/>

But this one doesn't work:

background-image: url("images/example.png");

Could anybody explain why and suggest how to solve this problem?

1

There are 1 answers

5
xiaofeng.li On

Since partial URLs are relative to the source of the style sheet, and your paths structure looks like this:

/images/example.png
/css/example.css

So image URLs in example.css should either be absolute (/images/example.png), or have the correct relative path (../images/example.png).