我在Spark应用程序中为静态文件指定了一个位置:
Spark.staticFileLocation("/public")
Run Code Online (Sandbox Code Playgroud)
现在我想为某些文件添加一个过滤器(例如出于安全目的),但它不起作用:
Spark.before("/admin.html", myFilter);
Run Code Online (Sandbox Code Playgroud)
但是,对于非静态映射,它确实有效.是否可以为静态文件配置这样的过滤器?
换句话说,Spark保护静态文件(如管理页面的模板)在没有身份验证的情况下暴露的最佳做法是什么?
小智 9
你可以使用Spark StaticFilesConfiguration,只是不要使用内置接线.Spark.staticFileLocation("/public")在检查任何其他过滤器或路由之前创建并发送响应.试试这个:
package web;
import spark.Service;
import spark.staticfiles.StaticFilesConfiguration;
public class ServerExample {
public ServerExample() {
Service service = Service.ignite();
service.port(1234);
// All other filters first
service.before((request, response) -> { /* Authentication filter */ });
service.before("/admin.html", (request, response) ->
service.halt(401, "Nothing to see here"));
service.before((request, response) -> { /* Some other filter */ });
// Static files filter is LAST
StaticFilesConfiguration staticHandler = new StaticFilesConfiguration();
staticHandler.configure("/public");
service.before((request, response) ->
staticHandler.consume(request.raw(), response.raw()));
// All your routes (are belong to us)
service.get("/", (req, res) -> "Hello world");
service.get("/health", (req, res) -> "Peachy");
}
public static void main(String[] args) {
new ServerExample();
}
}
Run Code Online (Sandbox Code Playgroud)
从长远来看,你可能想要提供来自Nginx或Apache的静态文件,如果你真的成功了,那就是CDN :)
| 归档时间: |
|
| 查看次数: |
2216 次 |
| 最近记录: |