EL表达式语言中如何访问对象${} [英] How to access objects in EL expression language ${}
问题描述
如果我有一个
ArrayList<Person> persons
我如何在 EL 中访问它?
How do I access it in EL?
<c:foreach items="${what goes here??}" var="person">${person.title}</c:foreach>
推荐答案
${foo}
在幕后使用的表达式 JspContext#findAttribute()
搜索属性在 PageContext
中, HttpServletRequest
, HttpSession
和 ServletContext
在这个通过他们的 getAttribute("foo")
方法排序,其中 foo
from ${foo}
因此代表属性名称 "foo"
一个d 返回第一个非空对象.
The expression ${foo}
uses behind the scenes JspContext#findAttribute()
which searches for attributes in PageContext
, HttpServletRequest
, HttpSession
and ServletContext
in this order by their getAttribute("foo")
method whereby foo
from ${foo}
thus represents the attribute name "foo"
and returns the first non-null object.
所以,如果你在 servlet 中做
So, if you do in a servlet
ArrayList<Person> persons = getItSomehow();
request.setAttribute("persons", persons); // It's now available by ${persons}
request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response);
并通过 URL 调用这个 servlet,然后你就可以在 page.jsp
中迭代它,如下所示:
And call this servlet by URL, then you'll be able to iterate over it in page.jsp
as follows:
<c:foreach items="${persons}" var="person">
${person.title}
<c:forEach>
当您将其放入会话范围时,上述内容也同样有效
The above is also equally valid when you put it in the session scope instead
request.getSession().setAttribute("persons", persons);
甚至在应用范围内
getServletContext().setAttribute("persons", persons);
EL 将为 ${person.title}
中的 title
隐式寻找一个以 get
为前缀的公共实例(非静态!)方法在 Person
类中,如下所示:
EL will for title
in ${person.title}
implicitly look for a public instance (not static!) method prefixed with get
in Person
class like below:
public String getTitle() {
return title;
}
字段 title
不一定需要存在于类中(因此您甚至可以返回硬编码字符串并继续使用 ${person.title}
),并且它不一定需要是实例字段(因此它也可以是静态字段,只要 getter 方法本身不是静态的).
The field title
does not necessarily need to exist in the class (so you can even return a hardcoded string and keep using ${person.title}
), and it does not necessarily need to be an instance field (so it can also be a static field, as long as the getter method itself isn't static).
只有boolean
(不是Boolean
!)getter 有特殊处理;EL 会隐式地寻找一个以 is
为前缀的公共方法.例如.对于 ${person.awesome}
:
Only boolean
(not Boolean
!) getters have a special treatment; EL will implicitly look for a public method prefixed with is
. E.g. for a ${person.awesome}
:
public boolean isAwesome() {
return awesome;
}
另见:
- 我们的 EL 维基页面
- servlet 如何工作?实例化、会话、共享变量和多线程
- 如何避免在 JSP 文件中使用 Java 代码?
- 在 HTML 中显示 JDBC 结果集在 JSP 页面中使用 MVC 和 DAO 模式
- 在scriptlet中直接使用EL ${XY} <% XY %>
- Java 是如何表达的语言解析布尔属性?(在 JSF 1.2 中)
这篇关于EL表达式语言中如何访问对象${}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!