gpt4 book ai didi

java - 使用 Spark Framework 为静态文件设置特定的 URL

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:51:40 24 4
gpt4 key购买 nike

我正在使用 Spark 为网页提供服务。对于静态文件,我将 Spark 初始化为 stated here :

所以我有这个结构:

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

我制作了 foo 文件夹来做个小把戏,因为我的网页位于 /foo url 下。像这样:

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

所以我的静态文件是这样加载的,例如:

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

我现在想要的是拥有这个路径变量。因为我有不同的环境,例如,如果我在另一个域中部署这个应用程序,我希望它是:

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

但是为此我必须更改版本并更改文件夹...

对于 Controller ,我很容易做到:

例子:

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

this.appBasePath 来自加载决定环境的配置。

所以我要问的是在不创建任何文件夹的情况下以编程方式设置静态文件 URL。有什么办法可以实现吗?

最佳答案

我最终通过为我所有的静态文件生成一个获取路径来解决这个问题。完全有可能有更简单的方法直接在 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 "";
} );
});

关于java - 使用 Spark Framework 为静态文件设置特定的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28224481/

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