您的位置:首页 > 编程语言 > Java开发

El中调用java静态方法

2015-10-30 09:58 465 查看
最近在项目中遇到需要调用静态方法的问题,形如:

<c:forEach items="beans" var="bean">
<p>总数:${com.example.Tools.getTotal(bean.nums)}</p>
</c:forEach>

不过上面的代码不能通过编译,只能寻求其他办法。经过查阅各种文档,找到了3种解决办法。

1,直接为Bean创建一个get方法

public double getTotal(){
return com.example.Tools.getTotal(nums);
}

然后在EL中直接使用:

总数:${bean.total}

2,将Tools#getTotal创建为一个EL function。首先创建一个
/WEB-INF/my.tld
文件:

<?xml version="1.0" encoding="UTF-8" ?>
<taglib
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1">

<display-name>Custom Functions</display-name>
<tlib-version>1.0</tlib-version>
  <short-name>my</short-name><!--short-name元素可不写 -->
<uri>http://example.com/functions</uri>

<function>
<name>calculateTotal</name>
<function-class>com.example.Tools</function-class>
<function-signature>double getTotal(double[])</function-signature>
</function>
</taglib>

然后在web.xml中定义uri和tld文件路径的映射:

<jsp-config>
<taglib>
<taglib-uri>http://example.com/functions</taglib-uri>
<taglib-location>/WEB-INF/my.tld</taglib-location>
</taglib>
</jsp-config>

接着在要使用的jsp头部引入该taglib:

<%@ taglib uri="http://example.com/functions" prefix="my" %>

其中uri对应web.xml中的taglib-uri。最后就可以在EL中使用该函数了:

<c:forEach items="beans" var="bean">
<p>总数:${my:calculateTotal(bean.nums)}</p>
</c:forEach>

3,使用Spring的SpEL:

jsp头部引入:

<%@taglib prefix="s" uri="http://www.springframework.org/tags" %>

使用:

<c:forEach items="beans" var="bean">
<s:eval expression="T(com.example.Tools).getTotal(bean.nums)" var="total" />
<p>总数:${total}</p>
</c:forEach>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: