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);
}
}
}
```