如何使用 EL 在 JSP 中获取 request/session/servletcontext 属性? [英] How to obtain request / session / servletcontext attribute in JSP using EL?
问题描述
我知道这并不难,但我运气不好.
I know this isn't hard, but I'm not having any luck.
我想让 fooList
从一个 JSP 中的 Servlet 可用.所以在 Servlet 中我有:
I want to make fooList
from a Servlet available in a JSP. So in the Servlet I have:
request.setAttribute("list", fooList);
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/myJsp.jsp");
dispatcher.forward(request, response);
然后在 JSP 中,我想要:
Then in the JSP, I want:
<c:forEach var="post" items="${SOME_EL_HERE}">
<!-- stuff -->
</c:forEach>
其中 SOME_EL_HERE
是检索我在 request
上设置的属性的表达式.
Where SOME_EL_HERE
is an expression that retrieves the attribute that I have set on the request
.
有什么想法吗?我的偏好是不通过添加框架使简单的任务复杂化,但我愿意改变策略.
Any thoughts? My preference is to not complicate a simple task by adding a framework, but I'm open to changes in strategy.
推荐答案
这只是您在此处设置的属性 name:
It's just the attribute name as you've set yourself here:
request.setAttribute("list", fooList);
就是这样 "list"
:
${list}
这对 session.setAttribute("name", value)
和 application.setAttribute("name", value)
的工作方式相同.该值在 EL 中仅通过 ${name}
可用.
This works the same way for session.setAttribute("name", value)
and application.setAttribute("name", value)
. The value is in EL available by just ${name}
.
更多细节:EL 默认使用 PageContext#findAttribute()
随后扫描页面、请求、会话和应用程序范围,寻找匹配给定属性名称的第一个非空属性值.
More detail: EL uses by default PageContext#findAttribute()
which scans in subsequently the page, request, session and application scopes for the firstnext non-null attribute value matching the given attribute name.
如果你想为你在不同范围内有多个同名属性的情况明确指定范围,那么通常的方法是使用 ${pageScope}
, ${requestScope}
、${sessionScope}
或 ${applicationScope}
.例如
If you'd like to explicitly specify the scope for the case that you've multiple attributes with the same name in different scopes, then normal approach is to use ${pageScope}
, ${requestScope}
, ${sessionScope}
or ${applicationScope}
. E.g.
${requestScope.list}
另见:
- Java EE 5 中的统一表达式语言教程
这篇关于如何使用 EL 在 JSP 中获取 request/session/servletcontext 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!