如何使用EL表达式语言$ {}访问对象 [英] How to access objects in EL expression language ${}
问题描述
如果我有
ArrayList<Person> persons
如何在EL中访问它?
<c:foreach items="${what goes here??}" var="person">${person.title}</c:foreach>
推荐答案
表达式 $ {foo }
在后台使用 JspContext#findAttribute()
,它在 PageContext
, HttpServletRequest
, HttpSession
和 ServletContext
按照其 getAttribute( foo)
方法的顺序,其中 foo
来自 $ {foo}
表示属性n ame foo
并返回第一个非空对象。
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,然后就可以在<$ c中对其进行迭代$ c> 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将在<$ c中获得标题
$ c> $ {person.title} 隐式地在 get
为前缀的公共实例(不是静态的!)方法>人员类,如下所示:
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
!)吸气剂具有特殊待遇; 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 Wiki页面
- servlet如何工作?实例化,会话,共享变量和多线程
- 如何避免JSP文件中的Java代码?
- 使用MVC和DAO模式在JSP页面的HTML中显示JDBC ResultSet
- 直接在脚本<%XY%>中使用EL $ {XY} ;
- Java表达式语言如何解析布尔属性? (在JSF 1.2中)
- Our EL wiki page
- How do servlets work? Instantiation, sessions, shared variables and multithreading
- How to avoid Java code in JSP files?
- Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
- Use EL ${XY} directly in scriptlet <% XY %>
- How does Java expression language resolve boolean attributes? (in JSF 1.2)
See also:
这篇关于如何使用EL表达式语言$ {}访问对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!