gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:28:02 25 4
gpt4 key购买 nike

我有这个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>

我写了一个简单的java Http服务器。该服务器处理请求,从资源文件夹加载 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/");但是 href="css/example.css"

中的 CSS

也许我做错了什么,这种方法不好?如何将index.html返回给客户端并提供从服务器加载资源的能力?

最佳答案

根据您的问题快速制作了单级元素。使 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文件夹):

enter image description here

运行main方法并转到 http://localhost:8080/main

一切都应该正常工作。

注意在java代码中你应该改变一件事——文件系统中的路径。

PS基于 http://www.microhowto.info/howto/serve_web_pages_using_an_embedded_http_server_in_java.html

关于java - 从http服务器响应资源的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60203142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com