在 Filter 内执行并呈现 JSP

发布于 2024-11-06 20:35:43 字数 792 浏览 0 评论 0原文

我有一个包含页面顶部内容的 JSP,我们将其称为 header.jsp。出于性能原因,我想在构建页面的其余部分之前呈现此 JSP 并将其刷新给用户。 (有关性能优势的说明,请参阅此处

)可以认为要做到这一点是创建一个名为 FlushingFilter 的 Filter,并让它将 JSP 的内容写入响应,然后在执行链的其余部分之前将其刷新。作为概念验证,我手动将 header.jsp 转换为 FlushingFilter 内的一堆 response.getWriter().println() 调用,然后调用 response.getWriter().flush() ,然后调用 doFilter()继续过滤器链。这个 println() 设置产生了所需的行为,并且页面速度要快得多。

但在启动之前,如果可能的话,我希望通过以编程方式调用过滤器内部的 JSP 来使其更清晰,而不必手动调用 println() 。我发现的最接近的解决方案是这个问题的第一个答案,但是它涉及调用 RequestDispatcher 上的 include() 方法。据我所知,我无法访问过滤器内的任何 RequestDispatcher,尽管这可能只是我的 JSP/servlet 经验不足所致。

有谁知道我如何以编程方式调用这样的 JSP,并以字符串格式返回其输出?

I have a JSP that contains the content at the top of my page, let's call it header.jsp. I would like to render this JSP and flush it out to the user before building up the rest of my page, for performance reasons. (See here for an explanation of the performance benefit.)

The best way I can think to do this is to create a Filter called FlushingFilter, and have it write the contents of the JSP to the response and then flush it out before executing the rest of the chain. As a proof-of-concept, I manually converted header.jsp to a bunch of response.getWriter().println() calls inside my FlushingFilter, after which I call response.getWriter().flush() and then doFilter() to continue the filter chain. This println() setup yields the desired behavior, and the page is quite a bit faster.

But before launching, I'd like to make it cleaner if possible by programatically invoking the JSP inside of the filter instead of having to work with manual println() calls. The closest solution to this I've found is the first answer to this question, but it involves calling the include() method on RequestDispatcher. As far as I'm aware, I don't have access to any RequestDispatcher inside my filter, although that could just be my JSP/servlet inexperience talking.

Does anyone know how I can programatically invoke a JSP like this, and get back its output in String format?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何以畏孤独 2024-11-13 20:35:43

我知道,我无权访问过滤器内的任何 RequestDispatcher,尽管这可能只是我的 JSP/servlet 缺乏经验所致

它在过滤器中绝对可用。

request.getRequestDispatcher("/WEB-INF/header.jsp").include(request, response);
response.flushBuffer();

I'm aware, I don't have access to any RequestDispatcher inside my filter, although that could just be my JSP/servlet inexperience talking

It's definitely available in the filter.

request.getRequestDispatcher("/WEB-INF/header.jsp").include(request, response);
response.flushBuffer();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文