我正在使用Spark framework创建一个网络应用程序,我已经浏览了他们网站上的教程。目前,我正在处理他们的模板部分,但是我似乎无法让项目识别出我的 css 和模板位于我的资源文件夹中。
我正在使用 Netbeans 和 Maven 来管理我的依赖项。
任何人都可以帮助我弄清楚如何在这种环境中正确设置相对路径/创建项目文件夹吗?我是 Maven 和 Spark 的新手,所以请放轻松。
最佳答案
静态文件:
如果您的资源目录如下所示:
resources
└───public
├───css
│ style.css
├───html
│ hello.html
└───templates
template.ftl
您可以使用staticFiles.location("/public")
。这将使 /public
成为静态文件根目录。
然后您可以像这样访问 hello.html
:http://{host}:{port}/html/hello.html
如果您想在文件系统上使用外部位置,可以使用staticFiles.externalLocation(...)
,其工作方式与上面几乎相同。
Note:
staticFiles.externalLocation(...)
can be set to your project's resources directory, which means that the files will be automatically refreshed (useful for development)
更深入的解释可以在 the spark documentation 中找到。
配置您的模板引擎:
如果您已经设置了 staticFiles 位置,但 Spark 仍然无法找到您的模板,请尝试此操作。
Note: These examples are for the FreeMarker engine, though they should apply to other engines with minor tweaking.
浏览完examples后,默认情况下,new FreemarkerEngine()
似乎会在 spark/template/freemarker
中查找模板,而不是您的 staticFiles 位置。
您有两个选择:
1:将所有模板移至该目录
或
2:配置自己的引擎,定义路由时传递它
FreeMarkerEngine freemarker = new FreeMarkerEngine();
Configuration config = new Configuration();
config.setTemplateLoader(
new ClassTemplateLoader(YOUR_CLASS.class, "/templatedir"));
freemarker.setConfiguration(config);
关于java - Spark框架和相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39197742/