3

我正在尝试编写一个简单的网络服务器,该服务器将使用 java 中的 vertx 从本地文件系统提供一个 html 文件。出于某种原因,尽管我在资源文件夹中有我的 web/index.html,但下面的代码找不到该文件。我正在使用 IntelliJ,它会将这个文件夹复制到它为项目生成的类文件夹中。如果我给出绝对路径,它会按预期工作。我在做什么错或如何确定“web”文件夹是否是类路径的一部分?顺便说一句,我已经通过 IntelliJ 以及使用“mvn exec:java -Dexec.mainClass="test.vertx.VertxDriver" 的终端运行它进行了测试,但得到了相同的结果 - 找不到资源。

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);
        }
    }
}
4

1 回答 1

1

sendFile 不在类路径中搜索,要么您必须将相对路径从目标放置到 src,要么您必须添加一个 maven 规则以将文件复制到目标目录。

要确定您实际在哪里搜索文件,请添加logger.info(System.getProperties().getProperty("user.dir"));并检查如何找到正确的路径。

(这种方法具有路径遍历安全性如何,顺便说一句)

于 2014-02-20T22:02:30.980 回答