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

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

问题描述

如果我有

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;
}



另请参见:



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