编辑:我解决了我的问题。 (见下文。)
问题
我是 NetBeans 的新手,我遇到了一个问题,涉及将资源加载到我的 servlet 应用程序,该应用程序通过使用 Tomcat 作为服务器的 NetBeans 运行。一切都很好,直到我尝试使用 Mustache 模板库(在 Java 中)构建我的响应。此时,抛出一个异常:
com.github.mustachejava.MustacheException: File not under root: /opt/catalina/bin
这个异常是在我尝试编译模板文件的代码中抛出的。我将资源(模板文件)的路径提供给 MustacheFactory
的 compile
方法。我的代码如下所示:
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile(getFormTemplatePath());
我的研究
我查看了 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...]
我在以下网址在线找到了 Mustache 代码:
我假设的解决方案
我猜想在我选择和配置服务器时,一定有某种方法可以在 NetBeans 中配置应用程序,以解决这个问题。我试过的是 Mustache NetBeans servlet“File not under root”exception
等的谷歌搜索变体,但没有什么结果。我猜我什至对 NetBeans 的了解还不够,不知道应该使用哪些关键词进行搜索。甚至有可能我已经找到了解决方案,但当我看到它时不认识它。
有人知道我可以尝试什么吗?谢谢。
最佳答案
您可以改用其他重载 API
Mustache compile(Reader reader, String name);
就像这样,您可以更喜欢将 mustache 模板文件放在任何地方
File f = new File(templateFilePath);
Mustache mustache = mf.compile(new InputStreamReader(new FileInputStream(f),Charset.forName("UTF-8")),f.getName());
关于java - Mustache 在 NetBeans servlet 中抛出 "File not under root"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28357608/