java 从 servlet 获取对 JspContext/PageContext 的引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12056437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:25:58  来源:igfitidea点击:

obtain reference to JspContext/PageContext from a servlet

javajspjakarta-eeservlets

提问by Magnus

Does anyone know a way to get a JspContext reference from a servlet?

有人知道从 servlet 获取 JspContext 引用的方法吗?

I have a servlet that forwards to a Jsp and I'd like to set some PageContext variables from within the servlet so they're ready for consumption in the Jsp.

我有一个转发到 Jsp 的 servlet,我想从 servlet 内设置一些 PageContext 变量,以便它们准备好在 Jsp 中使用。

回答by Alonso Dominguez

Let me see if I understood: you want to invoke a JSP from a servlet and make some variables (which are under the control of the servlet) available to the JSP. Right?

让我看看我是否理解:您想从 servlet 调用 JSP 并使一些变量(在 servlet 的控制下)可用于 JSP。对?

Then forget about the PageContext, it's just specific to JSP pages and it can't be accessed from a servlet. Any attribute you set in the request, session or servlet context will be available in the JSP. The PageContextis a scope wider than the previous ones and it comes with a findAttributemethod that, when invoked, will look for an attribute with given name inside the page's context, request, session or servlet context (in that order).

然后忘记PageContext,它只是特定于 JSP 页面,不能从 servlet 访问。您在请求、会话或 servlet 上下文中设置的任何属性都将在 JSP 中可用。这PageContext是一个比以前更广泛的范围,它带有一个findAttribute方法,当调用时,它将在页面的上下文、请求、会话或 servlet 上下文(按该顺序)中查找具有给定名称的属性。

So, the only thing you need is to set those variables as attributes in one of those scopes, I would suggest to use the requestone (HttpServletRequest.setAttribute("foo", "fooValue")) and then use it in your JSP using a value expression (${foo}).

因此,您唯一需要做的就是将这些变量设置为这些范围之一中的属性,我建议使用request一个 ( HttpServletRequest.setAttribute("foo", "fooValue")),然后使用值表达式 ( ${foo})在您的 JSP 中使用它。

回答by rickz

You should use request scope. A pageContext is obtained by a implementation dependent subclass of JspFactory in the service method of the JSP. In Tomcat, for example

您应该使用请求范围。一个pageContext是通过JSP的service方法中JspFactory的一个实现依赖子类获取的。以Tomcat为例

public void _jspService(
 ...
pageContext = _jspxFactory.getPageContext(this, request, response,null, true, 8192, true); 

So pageContext doesn't exist before the request is sent to the JSP.

所以在请求被发送到 JSP 之前 pageContext 不存在。