可以通过以下方式在 “/home” 路由上提供静态文件。

huangapple go评论195阅读模式
英文:

Is there a way where I can serve static files one /home route

问题

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 <button>Click</button> 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.

  1. import com.sun.net.httpserver.HttpHandler;
  2. import com.sun.net.httpserver.HttpExchange;
  3. import java.io.IOException;
  4. import java.io.OutputStream;
  5. import java.net.InetSocketAddress;
  6. import java.nio.file.Files;
  7. import java.nio.file.Path;
  8. import java.nio.file.Paths;
  9. public class App {
  10. public static void main(String[] args) throws IOException {
  11. int port = 8080;
  12. HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
  13. server.createContext("/home", new RequestHandler());
  14. server.start();
  15. System.out.println("Server started on port " + port);
  16. }
  17. }
  18. class RequestHandler implements HttpHandler {
  19. @Override
  20. public void handle(HttpExchange exchange) throws IOException {
  21. String requestPath = exchange.getRequestURI().getPath();
  22. if (requestPath.equals("/home")) {
  23. serveFile(exchange, "Views/index.html", "text/html");
  24. serveFile(exchange, "Views/style.css", "text/css");
  25. } else {
  26. // Handle other requests here
  27. // For example, you could serve a 404 page
  28. String response = "404 - Not Found";
  29. exchange.sendResponseHeaders(404, response.length());
  30. try (OutputStream os = exchange.getResponseBody()) {
  31. os.write(response.getBytes());
  32. }
  33. }
  34. }
  35. private void serveFile(HttpExchange exchange, String filePath, String contentType) throws IOException {
  36. Path path = Paths.get(filePath);
  37. byte[] fileBytes = Files.readAllBytes(path);
  38. exchange.getResponseHeaders().set("Content-Type", contentType);
  39. exchange.sendResponseHeaders(200, fileBytes.length);
  40. try (OutputStream os = exchange.getResponseBody()) {
  41. os.write(fileBytes);
  42. }
  43. }
  44. }
英文:

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 <button>Click</button> 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.

  1. import com.sun.net.httpserver.HttpHandler;
  2. import com.sun.net.httpserver.HttpExchange;
  3. import java.io.IOException;
  4. import java.io.OutputStream;
  5. import java.net.InetSocketAddress;
  6. import java.nio.file.Files;
  7. import java.nio.file.Path;
  8. import java.nio.file.Paths;
  9. public class App {
  10. public static void main(String[] args) throws IOException {
  11. int port = 8080;
  12. HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
  13. server.createContext(&quot;/home&quot;, new RequestHandler());
  14. server.start();
  15. System.out.println(&quot;Server started on port &quot; + port);
  16. }
  17. }
  18. class RequestHandler implements HttpHandler {
  19. @Override
  20. public void handle(HttpExchange exchange) throws IOException {
  21. String requestPath = exchange.getRequestURI().getPath();
  22. if (requestPath.equals(&quot;/home&quot;)) {
  23. serveFile(exchange, &quot;Views/index.html&quot;, &quot;text/html&quot;);
  24. serveFile(exchange, &quot;Views/style.css&quot;, &quot;text/css&quot;);
  25. } else {
  26. // Handle other requests here
  27. // For example, you could serve a 404 page
  28. String response = &quot;404 - Not Found&quot;;
  29. exchange.sendResponseHeaders(404, response.length());
  30. try (OutputStream os = exchange.getResponseBody()) {
  31. os.write(response.getBytes());
  32. }
  33. }
  34. }
  35. private void serveFile(HttpExchange exchange, String filePath, String contentType) throws IOException {
  36. Path path = Paths.get(filePath);
  37. byte[] fileBytes = Files.readAllBytes(path);
  38. exchange.getResponseHeaders().set(&quot;Content-Type&quot;, contentType);
  39. exchange.sendResponseHeaders(200, fileBytes.length);
  40. try (OutputStream os = exchange.getResponseBody()) {
  41. os.write(fileBytes);
  42. }
  43. }
  44. }
  45. ```
  46. </details>
  47. # 答案1
  48. **得分**: 1
  49. 当浏览器加载一个HTML文件并遇到对外部CSS文件的链接时,它会发起单独的请求来获取CSS文件。您当前的实现尝试在单个响应中为/home路由提供HTML和CSS内容,这是不正确的。
  50. 以下是修复此问题的方法:
  51. 修改您的index.html以引用style.css作为相对路径:
  52. 基本上,您应该将此内容放在**head**标签中:
  53. ```html
  54. <link rel="stylesheet" href="/Views/style.css">
英文:

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:
<br> Basicly you should this inside head tag

  1. &lt;link rel=&quot;stylesheet&quot; href=&quot;/Views/style.css&quot;&gt;

huangapple
  • 本文由 发表于 2023年8月11日 02:12:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76878331.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定