8

私はSparkを使用してWebページを提供しています..静的ファイルについては、ここに記載されているようにSparkを初期化します:

だから私はこの構造を持っています:

/src/main/resources/public/
                      |-- foo/
                           |-- css/
                           |    |-- bootstrap.css
                           |-- js/
                           |    ...
                           |-- img/
                                ...

fooのウェブページはURLの下にあるので、トリックを作るためにフォルダを作成しました/foo..次のように:

http://www.example.com/foo/index

したがって、私の静的ファイルは、たとえば次のようにロードされます。

http://www.example.com/foo/css/bootstrap.css

私が今欲しいのは、このパス変数を持つことです..私はさまざまな環境を持っているため、たとえば、このアプリを別のドメインにデプロイする場合は、次のようにしたいと考えています。

http://www.example2.com/superfoo/css/bootstrap.css

しかし、このためには、リリースを変更してフォルダーを変更する必要があります...

コントローラーの場合、これを簡単に作成しました:

例:

    Spark.get(this.appBasePath + "/users", (request, response) -> {
        return this.getUsersView(request);
    }, new FreeMarkerEngine());

this.appBasePath環境を決定するためにロードされる構成に由来します。

だから私が求めているのは、フォルダーを作成せずにプログラムで静的ファイルの URL を設定することです。これを達成する方法はありますか?

4

1 に答える 1

5

すべての静的ファイルの取得ルートを生成することで、この問題を回避することになりました。これを直接 spark で行うもっと簡単な方法がある可能性は十分にありますが、spark.resourceパッケージの詳細を理解するよりも、このコードを書く方が時間はかかりませんでした。

最初に、特定のリソース ディレクトリ内のすべてのファイルを反復処理できるように、いくつかのヘルパー関数を定義します (Java 8 が必要です)。

/**
 * Find all resources within a particular resource directory
 * @param root base resource directory. Should omit the leading / (e.g. "" for all resources)
 * @param fn Function called for each resource with a Path corresponding to root and a relative path to the resource.
 * @throws URISyntaxException
 */
public static void findResources(String root,BiConsumer<Path,Path> fn) throws URISyntaxException {
    ClassLoader cl = Main.class.getClassLoader();
    URL url = cl.getResource(root);     
    assert "file".equals(url.getProtocol());
    logger.debug("Static files loaded from {}",root);
    Path p = Paths.get(url.toURI());
    findAllFiles(p, (path) -> fn.accept(p,p.relativize(path)) );
}
/**
 * Recursively search over a directory, running the specified function for every regular file.
 * @param root Root directory
 * @param fn Function that gets passed a Path for each regular file
 */
private static void findAllFiles(Path root, Consumer<Path> fn) {
    try( DirectoryStream<Path> directoryStream = Files.newDirectoryStream(root)) {
        for(Path path : directoryStream) {
            if(Files.isDirectory(path)) {
                findAllFiles(path, fn);
            } else {
                fn.accept(path);
            }
        }
    } catch (IOException ex) {}
}

次に、これを使用して、各ファイルの新しい GET ルートを定義します

String webroot = "/server1";
findResources("static", (root,path) -> {
    String route = webroot+"/"+path;
    String resourcePath = "/static/"+path.toString();
    logger.debug("Mapping {} to {}",route, resourcePath);
    get(webroot+"/"+path, (req,res) -> {
        Files.copy(root.resolve(path), res.raw().getOutputStream());
        AbstractFileResolvingResource resource = new ExternalResource(resourcePath);
        String contentType = MimeType.fromResource(resource);
        res.type(contentType );
        return "";
    } );
});
于 2016-11-11T21:17:29.793 に答える