El中调用静态方法

最近在项目中遇到需要调用静态方法的问题,形如:

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

转载于:https://my.oschina.net/u/141940/blog/760829

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值