步骤:
(1)自定义类 和方法(public +static)
- package edu.study.struts;
- public class TestFunction {
- /**
- *
- * 自定义类和方法 ,方法必须是public + static
- * @param name
- * @return
- */
- public static String Hello(String name){
- return " you are a newcomer here, "+name;
- }
- }
千万要铭记:Hello()必须是public static 的。
(2)编写自定义 tld 文件,将此自定义tld文件放在WEB-INF或者WEB-INF的任意子目录下
- <?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">
- <description>test own defined functions library</description>
- <display-name>test functions</display-name>
- <tlib-version>1.0</tlib-version>
- <short-name>test</short-name>
- <uri>http://edu.study.struts/functions</uri>
- <function>
- <name>testFunction</name>
- <function-class>edu.study.struts.TestFunction</function-class>
- <function-signature>java.lang.String Hello(java.lang.String)</function-signature>
- </function>
- </taglib>
说明:
A:标签<description>、<description-name>、<tlib-version>、<short-name>、<uri>内容随意,注意这里设置的uri后面jsp中要引入。
B:<function> 标签中的<name>标签在JSP中要作为函数名调用,这里的名字可以和实际的函数名一致,也可以不一致,可认为是实际函数名的别名。
C:<function-class>标签是 包名+类名 (自定义类)。
D:<function-signature>是自定义函数的说明,如果是包装类型,需写完整路径;如果是基本数据类型,则不需要。如下又一示例所示:
- <function>
- <description>
- Returns the index withing a string of the first occurrence of a specified substring.
- </description>
- <name>indexOf</name>
- <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
- <function-signature>int indexOf(java.lang.String, java.lang.String)</function-signature>
- <example>
- ${fn:indexOf(name, "-")}
- </example>
- </function>
(3)在要使用自定义函数库的JSP页面中引入
- <%@ taglib prefix="test" uri="http://edu.study.struts/functions" %>
(4)使用:${前缀 + 冒号 + 函数的别名 }
- <body>
- <h1>测试JSTL--自定义函数库</h1>
- <span style="color:#006600;"> </span> ${test:testFunction("胡同学") }
- </body>
(5)结果
测试JSTL--自定义函数库
you are a newcomer here, 胡同学