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

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

问题描述

如何使用JSTL/EL从JSP从Java类中调用带有在Java类中定义的参数的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,等),并声明web.xml符合Servlet 3.0.此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天全站免登陆