EL表达式语言中如何访问对象${} [英] How to access objects in EL expression language ${}

查看:33
本文介绍了EL表达式语言中如何访问对象${}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个

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, HttpSessionServletContext 在这个通过他们的 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;
}

另见:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆