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

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

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.

    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);
            }
        }
    }
英文:

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.

   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(&quot;/home&quot;, new RequestHandler());
           server.start();
   
           System.out.println(&quot;Server started on port &quot; + port);
       }
   }
   
   class RequestHandler implements HttpHandler {
       @Override
       public void handle(HttpExchange exchange) throws IOException {
           String requestPath = exchange.getRequestURI().getPath();
           
           if (requestPath.equals(&quot;/home&quot;)) {
               serveFile(exchange, &quot;Views/index.html&quot;, &quot;text/html&quot;);
               serveFile(exchange, &quot;Views/style.css&quot;, &quot;text/css&quot;);
           } else {
               // Handle other requests here
               // For example, you could serve a 404 page
               String response = &quot;404 - Not Found&quot;;
               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(&quot;Content-Type&quot;, contentType);
           exchange.sendResponseHeaders(200, fileBytes.length);
   
           try (OutputStream os = exchange.getResponseBody()) {
               os.write(fileBytes);
           }
       }
   }
   ```



</details>


# 答案1
**得分**: 1

当浏览器加载一个HTML文件并遇到对外部CSS文件的链接时,它会发起单独的请求来获取CSS文件。您当前的实现尝试在单个响应中为/home路由提供HTML和CSS内容,这是不正确的。

以下是修复此问题的方法:

修改您的index.html以引用style.css作为相对路径:
基本上,您应该将此内容放在**head**标签中:

```html
<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

&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:

确定