在过滤器内执行和呈现JSP [英] Execute and render JSP inside a Filter

查看:95
本文介绍了在过滤器内执行和呈现JSP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSP,它包含页面顶部的内容,我们将其称为header.jsp.出于性能原因,我想在构建页面的其余部分之前呈现此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.)

我认为做到这一点的最佳方法是创建一个名为FlushingFilter的Filter,并使其将JSP的内容写入响应中,然后在执行该链的其余部分之前将其清除.作为概念验证,我在FlushingFilter内部手动将header.jsp转换为一堆response.getWriter().println()调用,然后再调用response.getWriter().flush()和doFilter()继续过滤链.此println()设置会产生所需的行为,并且页面要快得多.

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.

但是在启动之前,我希望通过以编程方式在过滤器内部调用JSP来使其变得更干净,而不必使用手动的println()调用.我找到的最接近的解决方案是这个问题的第一个答案,但是它涉及在RequestDispatcher上调用include()方法.据我所知,我没有访问过滤器中的任何RequestDispatcher的权限,尽管那可能只是我的JSP/Servlet经验不足而引起的.

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.

有人知道我如何以编程方式调用这样的JSP,并以String格式返回其输出吗?

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

推荐答案

我知道,我无法访问过滤器中的任何RequestDispatcher,尽管这可能只是我的JSP/servlet经验不足

它肯定在过滤器中可用.

It's definitely available in the filter.

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

这篇关于在过滤器内执行和呈现JSP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆