java - 使用 <jsp :include> to make a servlet call that returns additional <jsp:include >'s, but they' re not being rendered

标签 java jsp servlets

所以这个问题建议在执行包含之前使用 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/

相关文章:

java - 为ReSTLet创建Servlet Web应用程序

java - Hibernate 是否支持 Postgres 9.2 Json 数据类型?

java - 使用 1 个 for 循环将整数插入数组

java - 设置 Java 环境 (Apache Tomcat) 以编码 UTF-8

java - 如何使用 JSTL、EL 检查 JSP 页面中浏览器的用户代理?

java - Readline 太慢了——还有更快的吗?

java.io.FileNotFoundException :/home/ec2-user/src/main/resources/keystore. jks(没有这样的文件或目录)

java - 如何设置 Unix 服务器文件夹的相对路径来保存/创建 Excel 文件

java - 在 JSP 代码中访问使用 XSL 文件的 XML 文件的概念和编程

jsp - 如何在不包含上下文根名称的情况下使用相对路径?