使用<jsp:include>进行servlet调用,返回额外的<jsp:include>,但它们没有被渲染</jsp:include> </jsp:include>

时间:2011-09-22 18:54:13

标签: java jsp servlets

所以这个问题建议在执行include之前使用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标记,指向我正在检查的文件。不幸的是,浏览器没有“包含”它。我收到的错误如“没有属性'页''和”元素'jsp:include'undefined' - 这表明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;
}

我觉得答案很接近,但我不确定我应该在后面看什么。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

不要将带有大量HTML和JSP标记的字符串写入响应。这毫无意义。 Web浏览器不了解JSP标记。

改为呼叫RequestDispatcher#include()

request.getRequestDispatcher(checkedJspPath).include(request, response);

将HTML移回JSP。


无关具体问题,我知道你指的是我的旧答案,但我意识到检查ServletContext#getResource()是否不返回{实际上更好{1}}而不是使用null。这样,只要不扩展WAR,它就能正常工作。