自定义函数的开发步骤非常类似于标签的开发步骤,区别在于自定义标签直接在页面上生成输出,而自定义函数则需要在表达式语言中使用;由于EL本身只是一种数据访问语言,因此它不支持调用方法。如果需要在EL中进行更复杂的处理,就可以通过函数来完成。函数的本质是:提供一种语法允许在EL中调用某个类的静态方法;
开发步骤:
(1)、开发函数处理类
函数处理类就是普通类,只要包含静态方法,这样静态方法都可定义成一个函数;
<span style="font-size:18px;">package lee;
public class Functions
{
// 对字符串进行反转
public static String reverse( String text )
{
return new StringBuffer( text ).reverse().toString();
}
// 统计字符串的个数
public static int countChar( String text )
{
return text.length();
}
}</span>
(2)、使用标签库定义函数
<span style="font-size:18px;"><?xml version="1.0" encoding="GBK"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
web-jsptaglibrary_2_0.xsd" version="2.0">
<tlib-version>1.0</tlib-version>
<short-name>crazyit</short-name>
<!-- 定义该标签库的URI -->
<uri>http://www.crazyit.org/tags</uri>
<!-- 定义第一个函数 -->
<function>
<!-- 定义函数名:reverse -->
<name>reverse</name>
<!-- 定义函数的处理类 -->
<function-class>lee.Functions</function-class>
<!-- 定义函数的实现方法-->
<function-signature>
java.lang.String reverse(java.lang.String)</function-signature>
</function>
<!-- 定义第二个函数: countChar -->
<function>
<!-- 定义函数名:countChar -->
<name>countChar</name>
<!-- 定义函数的处理类 -->
<function-class>lee.Functions</function-class>
<!-- 定义函数的实现方法-->
<function-signature>int countChar(java.lang.String)
</function-signature>
</function>
</taglib></span>
(3)、在JSP页面的EL中使用函数
<span style="font-size:18px;"><%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<%@ taglib prefix="crazyit" uri="http://www.crazyit.org/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> new document </title>
<meta name="website" content="http://www.crazyit.org" />
</head>
<body>
<h2>表达式语言 - 自定义函数</h2><hr/>
请输入一个字符串:
<form action="useFunctions.jsp" method="post">
字符串 = <input type="text" name="name" value="${param['name']}">
<input type="submit" value="提交">
</form>
<table border="1" bgcolor="aaaadd">
<tr>
<td><b>表达式语言</b></td>
<td><b>计算结果</b></td>
<tr>
<tr>
<td>\${param["name"]}</td>
<td>${param["name"]} </td>
</tr>
<!-- 使用reverse函数-->
<tr>
<td>\${crazyit:reverse(param["name"])}</td>
<td>${crazyit:reverse(param["name"])} </td>
</tr>
<tr>
<td>\${crazyit:reverse(crazyit:reverse(param["name"]))}</td>
<td>${crazyit:reverse(crazyit:reverse(param["name"]))} </td>
</tr>
<!-- 使用countChar函数 -->
<tr>
<td>\${crazyit:countChar(param["name"])}</td>
<td>${crazyit:countChar(param["name"])} </td>
</tr>
</table>
</body>
</html></span>
注意:自定义函数的实质:就是将指定Java类的静态方法暴露成可以在EL中使用的函数,所以可以定义成函数的方法必须用public static修饰;特别说明:如果能帮助到您,请您留下点滴痕迹,让我知道我的存在是有意义的;如果不能帮助到您,请接受我的歉意;