el自定义函数

来源:互联网 发布:javascript strict 编辑:程序博客网 时间:2024/06/06 04:51

 

这个有点小麻烦,配的东西有点多,简单记录一下建立流程
先写一个普通的java类,里面要在el中调用的函数要静态公有,比如:
package test;

public class ELFTests 
{
public static String add(int x,int y)
{
return (x + y) + "";
}

public static String sub(int x, int y)
{
return (x - y) + "";
}

//此方法无用
private static void exec()
{

}
}

然后给建立一个tld文件,创建方法见上一篇文章,要从schema web-jsptaglibrary_2_0来创建xml,如果创建的xml中的taglib等节点有前缀要把前缀去掉,在eclipse里编辑命名空间 就行了。然后给tlib-version赋值,1.0,然后就可以为刚才创建的类中的函数创建function节点了,比如:
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd ">
<tlib-version>1.0</tlib-version>
<short-name>elftest</short-name>
<function>
<name>add</name>
<function-class>test.ELFTests</function-class>
<function-signature>String add(int ,int)</function-signature>
</function>
<function>
<name>sub</name>
<function-class>test.ELFTests</function-class>
<function-signature>String sub(int ,int)</function-signature>
</function>
</taglib>

function的name还有function-signature都要跟类中的函数名完全一样,不然会找不到函数。

建好tld文件后,再在web.xml文件中的<jsp-config>节点中添加    <taglib>节点,比如:
<jsp-config>
<taglib>
<taglib-uri>elftest</taglib-uri>
<taglib-location>/WEB-INF/tlds/elftest.tld</taglib-location>
</taglib></jsp-config>
其中taglib-location的值为刚才创建的tld文件的位置,taglib-uri则随便定义一个就可以。最后在jsp网页中添加taglib指令
<%@ taglib prefix="elf" uri="elftest" %>
uri就写刚才在web.xml中定义的uri的值,prefix随便设就行了。然后在页面中调用如下:
${elf:add(2,4)}<br>
${elf:sub(2,4)}
用刚才定义的前缀:函数名就可以了。

 

原创粉丝点击