Mar*_*rio 2 java tomcat netbeans servlets mustache
编辑:我解决了我的问题。(见下文。)
问题
我是 NetBeans 的新手,我遇到了一个问题,涉及将资源加载到我的 servlet 应用程序,该应用程序通过 NetBeans 运行,使用 Tomcat 作为服务器。一切都很好,直到我尝试使用 Mustache 模板库(在 Java 中)构建我的响应。此时,抛出异常:
com.github.mustachejava.MustacheException: File not under root: /opt/catalina/bin
Run Code Online (Sandbox Code Playgroud)
这个异常是在我尝试编译模板文件的代码中抛出的。我喂路径资源(模板文件)的compile方法MustacheFactory。我的代码如下所示:
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile(getFormTemplatePath());
Run Code Online (Sandbox Code Playgroud)
我的研究
我查看了 Mustache 代码,尽我所知,这是发生了什么。Mustache 在加载资源时会进行安全检查,试图确保该资源位于文件系统中应用程序的根目录下。由于 NetBeans 使用某种魔法在 Tomcat 服务器上运行代码,而项目代码实际上位于文件系统的其他位置,Mustache 认为发生了一些可疑的事情。
换句话说,它可以找到文件;它只是不喜欢它在哪里找到它。似乎 Mustache/opt/catalina/bin作为应用程序的根,而模板文件实际上位于更像的路径:~/NetBeansProjects/MyProject/WEB-INF/template_file.mst.
Mustache 代码看起来像这样(这样你就可以检查我的推理):
try {
// Check to make sure that the file is under the file root or current directory.
// Without this check you might accidentally open a security whole when exposing
// mustache templates to end users.
File checkRoot = fileRoot == null ? new File("").getCanonicalFile() : fileRoot.getCanonicalFile();
File parent = file.getCanonicalFile();
while ((parent = parent.getParentFile()) != null) {
if (parent.equals(checkRoot)) break;
}
if (parent == null) {
throw new MustacheException("File not under root: " + checkRoot.getAbsolutePath());
}
// [Try-catch block continues...]
Run Code Online (Sandbox Code Playgroud)
我在以下 URL 在线找到了 Mustache 代码:
我假设的解决方案
我猜在选择和配置服务器时,必须有某种方法可以在 NetBeans 中配置应用程序,以解决这个问题。我尝试过的是谷歌搜索Mustache NetBeans servlet "File not under root" exception等等,但没有任何结果。我猜我对 NetBeans 的了解还不够,不知道应该用什么关键词来搜索。甚至有可能我已经找到了解决方案,但是当我看到它时却没有认出它。
有人知道我可以尝试什么吗?谢谢。
小智 5
您可以改用其他重载 API
Mustache compile(Reader reader, String name);
Run Code Online (Sandbox Code Playgroud)
就像这样,您可以更喜欢将 mustache 模板文件放在任何地方
File f = new File(templateFilePath);
Mustache mustache = mf.compile(new InputStreamReader(new FileInputStream(f),Charset.forName("UTF-8")),f.getName());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1344 次 |
| 最近记录: |