El中调用java静态方法
2024-08-24 09:07:23
最近在项目中遇到需要调用静态方法的问题,形如:
<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>
最新文章
- 从零开始学习Android(二)从架构开始说起
- jQuery中的Ajax几种请求方法
- centos svn服务器安装
- JSTL实现分页
- poj2378(树的dfs)
- C# 正则表达式 结合 委托
- sql关键字过滤C#方法
- Extensions in UWP Community Toolkit - Overview
- git push origin与git push -u origin master的区别
- STL中的拷贝替换算法(so easy)
- TCP/IP_网络基础知识
- [Umbraco] macro(宏)在umbraco中的作用
- js的各种正则表达式
- Vue组件(知识)
- Mybatis源码正确打开方式
- Swift之沙盒与数据存储
- FFmpeg 入门(6):音频同步
- (转) Linux 内核运行参数修改——sysctl命令
- outer join test
- github 管理图示