zoukankan      html  css  js  c++  java
  • El中调用java静态方法

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

    <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>
  • 相关阅读:
    C# 用Linq的方式实现对Xml文件的基本操作(创建xml文件、增删改查xml文件节点信息)
    Linq Like
    BS下实现WIN7下Aero效果
    Log4Net使用指南
    Sql 中取小数点后面两位小数.
    微软企业库回滚操作
    C#文件操作
    LinQ To XML——用LinQ查询XML
    Sql Server 字段类型说明
    Blog of the Day:几个中文技术类Blogger Groups
  • 原文地址:https://www.cnblogs.com/river2005/p/4922512.html
Copyright © 2011-2022 走看看