所以这个问题建议在执行包含之前使用 servlet 进行文件检查: How can you check if a file exists before including/importing it in JSP?
所以我写了一个 servlet 来完成这个任务。我用类似的东西来调用它
<jsp:include page='<%= "/servlet/fileChecker?section=THX&file=1138" &>'></jsp:include>
但是该 servlet 调用的输出包含一个 jsp:include 标记,指向我正在检查的文件。不幸的是,浏览器不“包含”它。我收到诸如“没有属性‘page’”和“元素‘jsp:include’未定义”之类的错误——这表明 servlet 输出没有呈现为 Java,而是呈现为 HTML。
这是输出:
<p>Text before the servlet call</p>
<p><h4>From THX1138</h4><jsp:include page='thx/results_1138.jsp'></jsp:include></p>
<p>Text after the servlet call</p>
这是我的 servlet 的主要调用:
private String FileChecker(String section, String file) {
String result = ""; // assume file does not exist
String pathToCheck = section + "/results_" + file + ".jsp";
// realPath is defined in the init() method as config.getServletContext().getRealPath("/");
File fileToCheck = new File(realPath + pathToCheck);
if (fileToCheck.exists()) {
result = "<p><h4>" + section + "</h4><jsp:include page='" + pathToCheck + "'></jsp:include></p>";
}
return result;
}
我觉得答案已经很接近了,但我不确定我应该看什么窗帘。有什么帮助吗?
最佳答案
不要将带有一堆 HTML 和 JSP 标记的字符串写入响应。这毫无意义。 Web 浏览器不理解 JSP 标记。
改为调用 RequestDispatcher#include()
。
request.getRequestDispatcher(checkedJspPath).include(request, response);
并将该 HTML 移回到 JSP 中。
<小时/>与具体问题无关,我知道您指的是我的旧答案,但我意识到实际上最好检查 ServletContext#getResource()
不会返回 null
,而是使用 File#exists()
。这样,只要 WAR 未展开,它就可以正常工作。
关于java - 使用 <jsp :include> to make a servlet call that returns additional <jsp:include >'s, but they' re not being rendered,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7519899/