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

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

最新文章

  1. e.target.files[0]层层剖析
  2. HTML基础(3)
  3. iOS AFNetworking 打印从服务器返回的错误提示信息
  4. Linux入门:运行级别解析
  5. $.getJSON( )的使用方法简介
  6. Egret 摇一摇功能
  7. 20145225《Java程序设计》 第4周学习总结
  8. 使用LotusScript操作Lotus Notes RTF域
  9. Partial Tree---hdu5534(完全背包)
  10. Hadoop学习笔记(3)——分布式环境搭建
  11. C#的三大特性
  12. hadoop可能遇到的问题
  13. Farewell, 2015, welcome 2016
  14. Delphi中的内存对齐 与 Packed关键字
  15. CentOS下使用tcpdump网络抓包
  16. JavaWeb 过滤器——验证登录 防止未登录进入界面
  17. SpringCloud学习1-服务注册与发现(Eureka)
  18. c语言第三例
  19. vue的指令绑定、事件、冒泡
  20. c#中如何保存焦点控件?

热门文章

  1. php session和cookie知识
  2. 建立自己的Servlet--成功
  3. xxx/labelKeypoint/utils/qt.py:81: RuntimeWarning: invalid value encountered in double_scalars
  4. SWIFT中获取配置文件路径的方法
  5. OK335xS UART device registe hacking
  6. zoj 1108 FatMouse&#39;s Speed 基础dp
  7. Navicat Premium连接PostgreSQL
  8. 【BZOJ1703】【usaco2007margold】ranking the cows 奶牛的魅力排名
  9. LG4768 [NOI2018]归程
  10. AllJoyn 了解