java—从http服务器响应资源的正确方法

44u64gxh  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(384)

我有这个index.html页面:

<html>
    <head>
     <title>My Site</title>
     <link rel="stylesheet" type="text/css" href="css/example.css" />
    </head>
    <body>
     <h2>Hello world</h2>
     <p>Image:</p>
     <img src="someimage.jpg" alt="W3Schools.com" width="104" height="142">
    </body>
   </html>

我编写了一个简单的javahttp服务器。此服务器处理请求,加载 index.html 从“资源”文件夹中选择并响应客户端(浏览器)。客户看到 index.html 但是没有资源(图像、css、js)。因为浏览器加载后 index.html 尝试加载此页中包含的所有资源。但是服务器中的资源。我写了一个新的处理程序 /assets/ 并试图替换中所有指向资源的链接 index.html 这样地:

<img src="someimage.jpg" width="104" height="142">

<img src="/assets/someimage.jpg" width="104" height="142">

在那之后 /assets/ 汉德勒,我切了uri的第一部分( /assets/ )并尝试从uri的第二部分加载资源( someimage.jpg );
它工作,但我不能加载css。因为我取代了 pageAsString.replace("src=\"", "/assets/"); 但是css在 href="css/example.css" 也许我做错了什么,而这种方法不好?如何将index.html返回给客户机并提供从服务器加载资源的能力?

col17t5w

col17t5w1#

根据你的问题做了一个简单的单班专题。使img和script标签起作用:

package test.server;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.URI;

public class MyHandler implements HttpHandler {
    public void handle(HttpExchange t) throws IOException, IOException {
        InputStream is = t.getRequestBody();

        InputStreamReader isReader = new InputStreamReader(is);
        BufferedReader reader = new BufferedReader(isReader);
        StringBuffer sb = new StringBuffer();
        String str;
        while((str = reader.readLine())!= null){
            sb.append(str);
        }

        String response = "<html>\n" +
                "\n" +
                "<head>\n" +
                "    <title>My Site</title>\n" +
                "    <link rel=\"stylesheet\" type=\"text/css\" href=\"css/example.css\" />\n" +
                "</head>\n" +
                "\n" +
                "<body>\n" +
                "    <h2>Hello world</h2>\n" +
                "    <p>Image:</p>\n" +
                "    <img src=\"/assets/cat.jpg\" alt=\"W3Schools.com\" width=\"104\" height=\"142\">\n" +
                "    <script src=\"/assets/alert.js\"></script>\n" +
                "</body>\n" +
                "\n" +
                "</html>";

        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
    }

    public static void main(String[] args) {

        InetSocketAddress cd = new InetSocketAddress(8080);
        HttpServer server = null;
        try {
            server = HttpServer.create(cd, 8080);
        } catch (IOException e) {
            e.printStackTrace();
        }

        server.createContext("/main", new MyHandler());

        server.createContext("/assets/", new HttpHandler() {
            @Override
            public void handle(HttpExchange httpExchange) throws IOException {
                String root = "!!! YOUR SITE ROOT IN FILE SYSTEM !!!";
                URI uri = httpExchange.getRequestURI();
                File file = new File(root + uri.getPath()).getCanonicalFile();
                if (!file.getPath().startsWith(root)) {
                    // Suspected path traversal attack: reject with 403 error.
                    String response = "403 (Forbidden)\n";
                    httpExchange.sendResponseHeaders(403, response.length());
                    OutputStream os = httpExchange.getResponseBody();
                    os.write(response.getBytes());
                    os.close();
                } else if (!file.isFile()) {
                    // Object does not exist or is not a file: reject with 404 error.
                    String response = "404 (Not Found)\n";
                    httpExchange.sendResponseHeaders(404, response.length());
                    OutputStream os = httpExchange.getResponseBody();
                    os.write(response.getBytes());
                    os.close();
                } else {
                    // Object exists and is a file: accept with response code 200.
                    httpExchange.sendResponseHeaders(200, 0);
                    OutputStream os = httpExchange.getResponseBody();
                    FileInputStream fs = new FileInputStream(file);
                    final byte[] buffer = new byte[0x10000];
                    int count = 0;
                    while ((count = fs.read(buffer)) >= 0) {
                        os.write(buffer,0,count);
                    }
                    fs.close();
                    os.close();
                }
            }
        });
        server.setExecutor(null); // creates a default executor
        server.start();
    }
}

alert.js可以是

alert("I'm from inner file!");
console.log("I'm from inner file!");

图像是任何jpg图像
项目结构(我们有src和assets文件夹):

运行main方法并转到http://localhost:8080/主
一切都应该正常。
请注意,在java代码中,您应该更改文件系统中的路径。
ps基于http://www.microhowto.info/howto/serve_web_pages_using_an_embedded_http_server_in_java.html

相关问题