基于JSTL自定义标签库

基于JSTL实现一个获取下拉列表信息的标签

1、在项目中添加jstl.jar的依赖

<dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
</dependency>
2、添加标签的功能类
package com.jd.jstl.action.tag;

import java.util.ArrayList;
import java.util.List;

public class UtilFunction {
    // 获取省份  

    public static List getProvinces() {
        List provinces = new ArrayList();

        // 暂时添加几个测试  
        provinces.add("广东省");
        provinces.add("广西省");
        provinces.add("山东省");
        provinces.add("四川省");
        provinces.add("江西省");

        return provinces;
    }
}
3、编写tld文件 mytags.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.jd.com/jstl/functions</uri>  
      
  <function>  
    <name>getProvinces</name>  
    <function-class>com.jd.jstl.action.tag.UtilFunction</function-class>  
    <function-signature>java.util.List getProvinces()</function-signature>  
  </function>  
</taglib>
4、在web.xml中添加自定义的taglib
<jsp-config>  
        <taglib>  
            <taglib-uri>http://www.jd.com/jstl/functions</taglib-uri>  
            <taglib-location>/WEB-INF/tags/mytags.tld</taglib-location>  
        </taglib>  
</jsp-config>
5、在jsp页面中使用自定义的tag
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="my" uri="http://www.jd.com/jstl/functions" %>  
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        省份:  
        <select name="provinces">  
            <option>--请选择省份--</option>  
            <c:forEach items="${my:getProvinces()}" var="p">  
                <option>${p }</option>
            </c:forEach>  
        </select>  
    </body>
</html>

你可能感兴趣的:(java,jstl,taglib)