1.写一个java类,类中写个返回一个集合的方法(UtilFunction.java)
package com.lxf.jstl;
import java.util.ArrayList;
import java.util.List;
/**
* 测试
* 自定义JSTL函数
* @author lxf
*/
public class UtilFunction {
// 获取省份
public static List<String> getProvinces() {
List<String> provinces = new ArrayList<String>();
// 暂时添加几个测试数据
provinces.add("湖南省");
provinces.add("浙江省");
provinces.add("广东省");
provinces.add("海南省");
provinces.add("湖北省");
provinces.add("江西省");
provinces.add("湖北省");
provinces.add("四川省");
provinces.add("江苏省");
provinces.add("福建省");
return provinces;
}
}
2.编写tld标签函数注册文件 ,放到WEB-INF目录下(myfunctions.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>
<short-name>my</short-name>
<uri>http://www.changtusoft.cn/test/functions</uri>
<!-- JSTL自定义函数 获取省份 -->
<function>
<name>getProvinces</name>
<function-class>com.lxf.jstl.UtilFunction</function-class>
<function-signature>java.util.List getProvinces()</function-signature>
</function>
</taglib>
3.在web.xml文件中注册tld(web.xml)
<?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>
<!-- 注册JSTL函数 -->
<jsp-config>
<taglib>
<taglib-uri>http://www.changtusoft.cn/test/functions</taglib-uri>
<taglib-location>/WEB-INF/myfunctions.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
4.编写jsp进行测试(index.jsp)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!-- 导入jstl标签库 -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!-- 导入自定义jstl标签库 -->
<%@ taglib prefix="my" uri="http://www.changtusoft.cn/test/functions" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>自定义JSTL函数</title>
</head>
<body>
<center>
<h2>自定义JSTL标签</h2>
省份:
<select name="provinces">
<option>--请选择省份--</option>
<c:forEach items="${my:getProvinces()}" var="p">
<option>${p }</option>
</c:forEach>
</select>
</center>
</body>
</html>
5.测试成功,非常完美。