为什么在JSP中需要pageContext? [英] Why there is a need of pageContext in JSP?
问题描述
当我们可以访问JSP中的所有隐式变量时,为什么要有 pageContext ?
When we can access all the implicit variables in JSP, why do we have pageContext ?
我的假设如下:使用EL表达式或JSTL来访问或设置我们需要的属性 pageContext 。让我知道我是否正确。
My assumption is the following: if we use EL expressions or JSTL, to access or set the attributes we need pageContext. Let me know whether I am right.
推荐答案
您需要它来访问非隐式变量。现在有道理吗?
You need it to access non-implicit variables. Does it now make sense?
更新:有时只想访问getter方法 HttpServletRequest
和 HttpSession
直接。在标准JSP中,这两个选项仅在 $ {pageContext}
中可用。以下是一些实际使用示例:
Update: Sometimes would just like to access the getter methods of HttpServletRequest
and HttpSession
directly. In standard JSP, both are only available by ${pageContext}
. Here are some real world use examples:
会话超时时刷新页面:
<meta http-equiv="refresh" content="${pageContext.session.maxInactiveInterval}">
将会话ID传递给Applet(这样可以在同一会话中与servlet通信):
Passing session ID to an Applet (so that it can communicate with servlet in the same session):
<param name="jsessionid" value="${pageContext.session.id}">
仅在会话的第一次请求时显示某些消息:
Displaying some message only on first request of a session:
<c:if test="${pageContext.session['new']}">Welcome!</c:if>
请注意,新
具有特殊之处处理,因为至少在EL 2.2中它是EL中的保留关键字。
note that new
has special treatment because it's a reserved keyword in EL, at least, since EL 2.2
显示用户IP:
Your IP is: ${pageContext.request.remoteAddr}
使链接相对于域,而无需对当前上下文路径进行硬编码:
Making links domain-relative without hardcoding current context path:
<a href="${pageContext.request.contextPath}/login">login</a>
动态定义< ; base>
标记(在 JSTL函数 taglib):
Dynamically defining the <base>
tag (with a bit help of JSTL functions taglib):
<base href="${fn:replace(pageContext.request.requestURL, pageContext.request.requestURI, pageContext.request.contextPath)}/">
Etcetera。在前面链接的 HttpServletRequest
和 HttpSession
javadoc中浏览一下,以了解所有这些getter方法。其中一些在JSP / EL中也可能有用。
Etcetera. Peek around in the aforelinked HttpServletRequest
and HttpSession
javadoc to learn about all those getter methods. Some of them may be useful in JSP/EL as well.
这篇关于为什么在JSP中需要pageContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!