1

I have root folder called TodoList this folder contains another folder called TodoList/Views/index.html,style.css my goal is to serve the index.html and the style.css on the route of /home however the index.html has one element Click and it has style which is to background-color blue orange for the button, but when I run the code on my localhost:8080 I am getting only the html file served not with its style. how can I make the html file keep its style rather than losing it midway thank you.

   import com.sun.net.httpserver.HttpHandler;
   import com.sun.net.httpserver.HttpExchange;
   
   import java.io.IOException;
   import java.io.OutputStream;
   import java.net.InetSocketAddress;
   import java.nio.file.Files;
   import java.nio.file.Path;
   import java.nio.file.Paths;
   
   public class App {
       public static void main(String[] args) throws IOException {
           int port = 8080;
           HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
   
           server.createContext("/home", new RequestHandler());
           server.start();
   
           System.out.println("Server started on port " + port);
       }
   }
   
   class RequestHandler implements HttpHandler {
       @Override
       public void handle(HttpExchange exchange) throws IOException {
           String requestPath = exchange.getRequestURI().getPath();
           
           if (requestPath.equals("/home")) {
               serveFile(exchange, "Views/index.html", "text/html");
               serveFile(exchange, "Views/style.css", "text/css");
           } else {
               // Handle other requests here
               // For example, you could serve a 404 page
               String response = "404 - Not Found";
               exchange.sendResponseHeaders(404, response.length());
               try (OutputStream os = exchange.getResponseBody()) {
                   os.write(response.getBytes());
               }
           }
       }
   
       private void serveFile(HttpExchange exchange, String filePath, String contentType) throws IOException {
           Path path = Paths.get(filePath);
           byte[] fileBytes = Files.readAllBytes(path);
   
           exchange.getResponseHeaders().set("Content-Type", contentType);
           exchange.sendResponseHeaders(200, fileBytes.length);
   
           try (OutputStream os = exchange.getResponseBody()) {
               os.write(fileBytes);
           }
       }
   }
   ```

Aliayub Ali
  • 83
  • 1
  • 7

1 Answers1

1

When a browser loads an HTML file and encounters a link to an external CSS file, it will make a separate request to fetch the CSS file. Your current implementation is trying to serve both the HTML and CSS content for the /home route in a single response, which is incorrect.

Here's a way to fix this:

Modify your index.html to reference the style.css as a relative path:
Basicly you should this inside head tag

<link rel="stylesheet" href="/Views/style.css">