我使用的Spark服务网页.对于静态文件我初始化星火喜欢这里所说:
所以我有这个结构:
/src/main/resources/public/
|-- foo/
|-- css/
| |-- bootstrap.css
|-- js/
| ...
|-- img/
...
Run Code Online (Sandbox Code Playgroud)
我制作了一个foo文件夹,因为我的网页位于/foourl ..这样:
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());
Run Code Online (Sandbox Code Playgroud)
this.appBasePath 来自加载决定环境的配置.
所以我要问的是以编程方式设置静态文件URL而不制作任何文件夹.有没有办法实现这个目标?
我最终通过为所有静态文件生成get路由来解决这个问题.完全可能有更简单的方法直接在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) {}
}
Run Code Online (Sandbox Code Playgroud)
然后我用它来为每个文件定义一个新的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 "";
} );
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3342 次 |
| 最近记录: |