一、创建UserDefinedELFunction类,用于处理函数业务
public class UserDefinedELFunction {
public static String toUpperCase(String s){
return s.toUpperCase();
}
}
二、在WEB-INF下创建userDefinedELFunction.tld文件
<?xml version="1.0" encoding="UTF-8"?>
<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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<!-- 版本号 -->
<tlib-version>1.0</tlib-version>
<!-- 短名称:一般和tld文件的文件名保持一致 -->
<short-name>elf</short-name>
<!-- 把tld文件绑定到一个名称空间上。只是一个名字,没有实际意义。 -->
<uri>http://www.xxx.com/jsp/functions</uri>
<function><!-- 定义函数 -->
<name>toUpperCase</name><!-- EL函数名称 -->
<function-class>com.xxx.functions.UserDefinedELFunction</function-class><!-- 方法所在的类全名 -->
<!-- 方法的签名:类的全名称。只有基本类型不需要 -->
<function-signature>java.lang.String toUpperCase( java.lang.String )</function-signature>
</function>
</taglib>
<!-- 版本号 -->
<tlib-version>1.0</tlib-version>
<!-- 短名称:一般和tld文件的文件名保持一致 -->
<short-name>elf</short-name>
<!-- 把tld文件绑定到一个名称空间上。只是一个名字,没有实际意义。 -->
<uri>http://www.xxx.com/jsp/functions</uri>
<function><!-- 定义函数 -->
<name>toUpperCase</name><!-- EL函数名称 -->
<function-class>com.xxx.functions.UserDefinedELFunction</function-class><!-- 方法所在的类全名 -->
<!-- 方法的签名:类的全名称。只有基本类型不需要 -->
<function-signature>java.lang.String toUpperCase( java.lang.String )</function-signature>
</function>
</taglib>
三、在web.xml中配置taglib,可省略
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
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-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!--
<jsp-config>
<taglib>
<taglib-uri>http://www.xxx.com/jsp/functions</taglib-uri>
<taglib-location>/WEB-INF/userDefinedELFunction.tld</taglib-location>
</taglib>
</jsp-config>
-->
</web-app>
<jsp-config>
<taglib>
<taglib-uri>http://www.xxx.com/jsp/functions</taglib-uri>
<taglib-location>/WEB-INF/userDefinedELFunction.tld</taglib-location>
</taglib>
</jsp-config>
-->
</web-app>
四、在JSP中映入taglib
<%@ page import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.xxx.com/jsp/functions" prefix="elf"%>
<html>
<head>
<title>自定义EL函数</title>
</head>
<body>
<%
pageContext.setAttribute("s", "abcdefg");
%>
${s}<br/>
${elf:toUpperCase(s)}<br/>
</body>
</html>
<%@ taglib uri="http://www.xxx.com/jsp/functions" prefix="elf"%>
<html>
<head>
<title>自定义EL函数</title>
</head>
<body>
<%
pageContext.setAttribute("s", "abcdefg");
%>
${s}<br/>
${elf:toUpperCase(s)}<br/>
</body>
</html>