我正在尝试编写一个简单的网络服务器,它使用 java 中的 vertx 从本地文件系统为 html 文件提供服务。出于某种原因,尽管我的 web/index.html 在资源文件夹中,但下面的代码找不到该文件。我正在使用 IntelliJ,它将此文件夹复制到它为项目生成的类文件夹。如果我给出绝对路径,它会按预期工作。我做错了什么,或者我如何确定“web”文件夹是否是类路径的一部分?顺便说一句,我已经通过使用“mvn exec:java -Dexec.mainClass="test.vertx.VertxDriver"从 IntelliJ 和终端运行它进行了测试,但得到了相同的结果 - 找不到资源。
package test.vertx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vertx.java.core.*;
import org.vertx.java.core.http.HttpServer;
import org.vertx.java.core.http.HttpServerRequest;
import java.io.IOException;
public class VertxDriver {
private static final Logger logger = LoggerFactory.getLogger(VertxDriver.class);
public static void main(String[] args) {
VertxDriver driver = new VertxDriver();
Vertx vertx = VertxFactory.newVertx();
HttpServer httpServer = vertx.createHttpServer();
httpServer.requestHandler(driver.new FileRequestHandler(vertx));
httpServer.listen(9999,"localhost");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
class FileRequestHandler implements Handler<HttpServerRequest> {
private Vertx vertx;
FileRequestHandler(Vertx vertx) {this.vertx = vertx;}
@Override
public void handle(HttpServerRequest httpServerRequest) {
String file = "";
if(httpServerRequest.path().equals("/")) {
file = "index.html";
}
logger.info("File being served is: "+file);
httpServerRequest.response().sendFile("web/"+file);
}
}
}
最佳答案
sendFile 不在类路径中搜索,要么您必须将目标的相对路径放在 src 中,要么必须添加 Maven 规则以将文件复制到目标目录。
要确定您实际搜索文件的位置,请添加 logger.info(System.getProperties().getProperty("user.dir"));
并检查如何找到正确的路径。
(顺便说一句,这种方法具有路径遍历安全性)
关于java - Vertx - 简单的网络服务器找不到 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21237769/