开发者

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

So this question suggested using a servlet to do the file check before doing the include: How can you check if a file exists before including/importing it in JSP?

So I wrote a servlet that does that. I call it using something like

<jsp:include page='<%= "/servlet/fileChecker?s开发者_如何转开发ection=THX&file=1138" &>'></jsp:include>

but the output of that servlet call contains a jsp:include tag, to the file I was checking for. Unfortunately, the browser doesn't "include" it. I'm getting errors like "there is no attribute 'page'" and "element 'jsp:include' undefined" -- which suggests the servlet output is not being rendered as Java but as HTML.

Here is the output:

<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>

Here is the main call of my 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;
}

I feel like the answer is close, but I'm not sure what curtain I should be looking behind. Any help?


Do not write a string with a bunch of HTML and JSP tags to the response. This makes no sense. The webbrowser does not understand JSP tags.

Call RequestDispatcher#include() instead.

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

And move that HTML back into the JSP.


Unrelated to the concrete question, I know that you're referring to an old answer of me, but I realize that it's actually better to check if ServletContext#getResource() doesn't return null instead of using File#exists(). This way it'll work as well whenever the WAR is not expanded.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜