如何使用 JSTL/EL 从 JSP 调用参数化方法 [英] How to call parameterized method from JSP using JSTL/EL

查看:30
本文介绍了如何使用 JSTL/EL 从 JSP 调用参数化方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用在 Java 类中定义的参数从 JSP 使用 JSTL/EL 调用 Java 方法.该方法正在返回数组.可以使用任何返回值.

How to call a Java method with arguments which is defined in Java class, from JSP using JSTL/EL. The method is returning arrays. Any return value can be used.

推荐答案

如果您的目标是和运行 Servlet 3.0 兼容容器(例如 Tomcat 7、Glassfish 3、JBoss AS 6、等)与声明符合 Servlet 3.0 的 web.xml.此 servlet 版本随 EL 2.2 一起提供,允许使用参数调用任意实例方法.

You can only invoke methods with arguments in EL if you're targeting and running a Servlet 3.0 compatible container (e.g. Tomcat 7, Glassfish 3, JBoss AS 6, etc) with a web.xml declared conform Servlet 3.0. This servlet version comes along with EL 2.2 which allows invoking arbitrary instance methods with arguments.

假设您在作用域中有一个 ${bean},它指的是一个类的实例,该类的方法类似于 public Object[] getArray(String key),那么你应该可以这样做:

Assuming that you've a ${bean} in the scope which refers to an instance of a class which has a method something like public Object[] getArray(String key), then you should be able to do this:

<c:forEach items="${bean.getArray('foo')}" var="item">
    ${item} <br />
</c:forEach>

甚至用另一个变量作为参数

or even with another variable as argument

<c:forEach items="${bean.getArray(foo)}" var="item">
    ${item} <br />
</c:forEach>

但是,如果您的目标不是 Servlet 3.0 容器,那么您根本无法在 EL 中调用带参数的方法.最好的办法是按照 Duffymo 的建议在预处理 servlet 中完成这项工作.

But if you don't target a Servlet 3.0 container, then you cannot invoke methods with arguments in EL at all. Your best bet is to just do the job in the preprocessing servlet as suggested by Duffymo.

Object[] array = bean.getArray("foo");
request.setAttribute("array", array);
// ...

作为一种完全不同的替代方法,您可以创建一个 EL 函数来委托方法调用.您可以在此博客的底部附近找到一个启动示例.您希望以如下方式结束:

As a completely different alternative, you could create an EL function which delegates the method call. You can find a kickoff example somewhere near the bottom of this blog. You'd like to end up something like as:

<c:forEach items="${util:getArray(bean, 'foo')}" var="item">
    ${item} <br />
</c:forEach>

public static Object[] getArray(Bean bean, String key) {
    return bean.getArray(key);
}

这篇关于如何使用 JSTL/EL 从 JSP 调用参数化方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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