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

<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. 从零开始学习Android(二)从架构开始说起
  2. jQuery中的Ajax几种请求方法
  3. centos svn服务器安装
  4. JSTL实现分页
  5. poj2378(树的dfs)
  6. C# 正则表达式 结合 委托
  7. sql关键字过滤C#方法
  8. Extensions in UWP Community Toolkit - Overview
  9. git push origin与git push -u origin master的区别
  10. STL中的拷贝替换算法(so easy)
  11. TCP/IP_网络基础知识
  12. [Umbraco] macro(宏)在umbraco中的作用
  13. js的各种正则表达式
  14. Vue组件(知识)
  15. Mybatis源码正确打开方式
  16. Swift之沙盒与数据存储
  17. FFmpeg 入门(6):音频同步
  18. (转) Linux 内核运行参数修改——sysctl命令
  19. outer join test
  20. github 管理图示

热门文章

  1. Win32 Debug &amp; Release
  2. nyoj743-复杂度 【排列组合】
  3. Spring boot starter pom的依赖关系说明
  4. ImageView小技巧
  5. 阅读笔记-A Message To Garcia
  6. catkin-tools
  7. Cairo编程
  8. DB2 SQL1477N问题
  9. BZOJ3170: [Tjoi2013]松鼠聚会 - 暴力
  10. Codeforces 612B. Wet Shark and Bishops 模拟