JSTL标签:自定义函数库

JSTL标签API地址:

http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html

 

下载地址:

http://jakarta.apache.org/site/downloads/downloads_taglibs-standard.cgi

项目中包含jstl.jar和standard.jar两个包。

在JSP页面中包含taglib.

如:
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

这些uri可以在对应的tld文件里面找到。

在jsp页面中使用jstl标签即可。一般结合EL一起使用。

如:<c:out value="${attr0}" default="kkkk"></c:out><br>

需要注意的是fn即函数标签一般使用在EL内部。。

如${fn:length("sfsfsff")}

因为操作的函数有可能没有提供给我们,所以在具体开发过程中可能要自己定义函数库。

默认函数库怎么做的呢?

函数类:

/*
 * Copyright 1999-2004 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ 

package org.apache.taglibs.standard.functions;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.jsp.JspTagException;

import org.apache.taglibs.standard.resources.Resources;
import org.apache.taglibs.standard.tag.common.core.Util;

/**
 * <p>JSTL Functions</p>
 * 
 * @author Pierre Delisle
 */

public class Functions {

    //*********************************************************************
    // String capitalization

    /**
     * Converts all of the characters of the input string to upper case.
     */
    public static String toUpperCase(String input) {
        return input.toUpperCase();
    }

    /**
     * Converts all of the characters of the input string to lower case.
     */
    public static String toLowerCase(String input) {
        return input.toLowerCase();
    }
    
    //*********************************************************************
    // Substring processing
    
    public static int indexOf(String input, String substring) {
        if (input == null) input = "";
        if (substring == null) substring = "";
        return input.indexOf(substring);
    }    

    public static boolean contains(String input, String substring) {
        return indexOf(input, substring) != -1;
    }    

    public static boolean containsIgnoreCase(String input, String substring) {
        if (input == null) input = "";
        if (substring == null) substring = "";        
        String inputUC = input.toUpperCase();
        String substringUC = substring.toUpperCase();
        return indexOf(inputUC, substringUC) != -1;
    }    

    public static boolean startsWith(String input, String substring) {
        if (input == null) input = "";
        if (substring == null) substring = "";
        return input.startsWith(substring);
    }    
        
    public static boolean endsWith(String input, String substring) {
        if (input == null) input = "";
        if (substring == null) substring = "";
        int index = input.indexOf(substring);
        if (index == -1) return false;
        if (index == 0 && substring.length() == 0) return true;
        return (index == input.length() - substring.length());
    }  
    
    public static String substring(String input, int beginIndex, int endIndex) {
        if (input == null) input = "";
        if (beginIndex >= input.length()) return "";
        if (beginIndex < 0) beginIndex = 0;
        if (endIndex < 0 || endIndex > input.length()) endIndex = input.length();
        if (endIndex < beginIndex) return "";
        return input.substring(beginIndex, endIndex);
    }    
    
    public static String substringAfter(String input, String substring) {
        if (input == null) input = "";
        if (input.length() == 0) return "";
        if (substring == null) substring = "";
        if (substring.length() == 0) return input;
        
        int index = input.indexOf(substring);
        if (index == -1) {
            return "";
        } else {
            return input.substring(index+substring.length());
        }
    }    
        
    public static String substringBefore(String input, String substring) {
        if (input == null) input = "";
        if (input.length() == 0) return "";
        if (substring == null) substring = "";
        if (substring.length() == 0) return "";

        int index = input.indexOf(substring);
        if (index == -1) {
            return "";
        } else {
            return input.substring(0, index);
        }
    }    

    //*********************************************************************
    // Character replacement
    
    public static String escapeXml(String input) {
        if (input == null) return "";
        return Util.escapeXml(input);
    }
    
    public static String trim(String input) {
        if (input == null) return "";
        return input.trim();
    }    

    public static String replace(
    String input, 
    String substringBefore,
    String substringAfter) 
    {
        if (input == null) input = "";
        if (input.length() == 0) return "";
        if (substringBefore == null) substringBefore = "";
        if (substringBefore.length() == 0) return input;
                
        StringBuffer buf = new StringBuffer(input.length());
        int startIndex = 0;
        int index;
        while ((index = input.indexOf(substringBefore, startIndex)) != -1) {
            buf.append(input.substring(startIndex, index)).append(substringAfter);
            startIndex = index + substringBefore.length();
        }
        return buf.append(input.substring(startIndex)).toString();
    }
    
    public static String[] split(
    String input, 
    String delimiters) 
    {
        String[] array;
        if (input == null) input = "";
        if (input.length() == 0) {
            array = new String[1];
            array[0] = "";
            return array;
        }
        
        if (delimiters == null) delimiters = "";

        StringTokenizer tok = new StringTokenizer(input, delimiters);
        int count = tok.countTokens();
        array = new String[count];
        int i = 0;
        while (tok.hasMoreTokens()) {
            array[i++] = tok.nextToken();
        }
        return array;
    }        
        
    //*********************************************************************
    // Collections processing
    
    public static int length(Object obj) throws JspTagException {
        if (obj == null) return 0;  
        
        if (obj instanceof String) return ((String)obj).length();
        if (obj instanceof Collection) return ((Collection)obj).size();
        if (obj instanceof Map) return ((Map)obj).size();
        
        int count = 0;
        if (obj instanceof Iterator) {
            Iterator iter = (Iterator)obj;
            count = 0;
            while (iter.hasNext()) {
                count++;
                iter.next();
            }
            return count;
        }            
        if (obj instanceof Enumeration) {
            Enumeration enum_ = (Enumeration)obj;
            count = 0;
            while (enum_.hasMoreElements()) {
                count++;
                enum_.nextElement();
            }
            return count;
        }
        try {
            count = Array.getLength(obj);
            return count;
        } catch (IllegalArgumentException ex) {}
        throw new JspTagException(Resources.getMessage("FOREACH_BAD_ITEMS"));        
    }      

    public static String join(String[] array, String separator) {
        if (array == null) return "";         
        if (separator == null) separator = "";
        
        StringBuffer buf = new StringBuffer();
        for (int i=0; i<array.length; i++) {
            buf.append(array[i]);
            if (i < array.length-1) buf.append(separator);
        }
        
        return buf.toString();
    }
}

 

对应的fn.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">
    
  <description>JSTL 1.1 functions library</description>
  <display-name>JSTL functions</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>fn</short-name>
  <uri>http://java.sun.com/jsp/jstl/functions</uri>

  <function>
    <description>
      Tests if an input string contains the specified substring.
    </description>
    <name>contains</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>boolean contains(java.lang.String, java.lang.String)</function-signature>
    <example>
      &lt;c:if test="${fn:contains(name, searchString)}">
    </example>
  </function>

  <function>
    <description>
      Tests if an input string contains the specified substring in a case insensitive way.
    </description>
    <name>containsIgnoreCase</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>boolean containsIgnoreCase(java.lang.String, java.lang.String)</function-signature>
    <example>
      &lt;c:if test="${fn:containsIgnoreCase(name, searchString)}">
    </example>
  </function>

  <function>
    <description>
      Tests if an input string ends with the specified suffix.
    </description>
    <name>endsWith</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>boolean endsWith(java.lang.String, java.lang.String)</function-signature>
    <example>
      &lt;c:if test="${fn:endsWith(filename, ".txt")}">
    </example>
  </function>

  <function>
    <description>
      Escapes characters that could be interpreted as XML markup.
    </description>
    <name>escapeXml</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>java.lang.String escapeXml(java.lang.String)</function-signature>
    <example>
      ${fn:escapeXml(param:info)}
    </example>
  </function>

  <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>

  <function>
    <description>
      Joins all elements of an array into a string.
    </description>
    <name>join</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>java.lang.String join(java.lang.String[], java.lang.String)</function-signature>
    <example>
      ${fn:join(array, ";")}
    </example>
  </function>

  <function>
    <description>
      Returns the number of items in a collection, or the number of characters in a string.
    </description>
    <name>length</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>int length(java.lang.Object)</function-signature>
    <example>
      You have ${fn:length(shoppingCart.products)} in your shopping cart.
    </example>
  </function>

  <function>
    <description>
      Returns a string resulting from replacing in an input string all occurrences
      of a "before" string into an "after" substring.
    </description>
    <name>replace</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>java.lang.String replace(java.lang.String, java.lang.String, java.lang.String)</function-signature>
    <example>
      ${fn:replace(text, "-", "&#149;")}
    </example>
  </function>

  <function>
    <description>
      Splits a string into an array of substrings.
    </description>
    <name>split</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>java.lang.String[] split(java.lang.String, java.lang.String)</function-signature>
    <example>
      ${fn:split(customerNames, ";")}
    </example>
  </function>

  <function>
    <description>
      Tests if an input string starts with the specified prefix.
    </description>
    <name>startsWith</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>boolean startsWith(java.lang.String, java.lang.String)</function-signature>
    <example>
      &lt;c:if test="${fn:startsWith(product.id, "100-")}">
    </example>
  </function>

  <function>
    <description>
      Returns a subset of a string.
    </description>
    <name>substring</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>java.lang.String substring(java.lang.String, int, int)</function-signature>
    <example>
      P.O. Box: ${fn:substring(zip, 6, -1)}
    </example>
  </function>

  <function>
    <description>
      Returns a subset of a string following a specific substring.
    </description>
    <name>substringAfter</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>java.lang.String substringAfter(java.lang.String, java.lang.String)</function-signature>
    <example>
      P.O. Box: ${fn:substringAfter(zip, "-")}
    </example>
  </function>

  <function>
    <description>
      Returns a subset of a string before a specific substring.
    </description>
    <name>substringBefore</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>java.lang.String substringBefore(java.lang.String, java.lang.String)</function-signature>
    <example>
      Zip (without P.O. Box): ${fn:substringBefore(zip, "-")}
    </example>
  </function>

  <function>
    <description>
      Converts all of the characters of a string to lower case.
    </description>
    <name>toLowerCase</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>java.lang.String toLowerCase(java.lang.String)</function-signature>
    <example>
      Product name: ${fn.toLowerCase(product.name)}
    </example>
  </function>

  <function>
    <description>
      Converts all of the characters of a string to upper case.
    </description>
    <name>toUpperCase</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>java.lang.String toUpperCase(java.lang.String)</function-signature>
    <example>
      Product name: ${fn.UpperCase(product.name)}
    </example>
  </function>

  <function>
    <description>
      Removes white spaces from both ends of a string.
    </description>
    <name>trim</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>java.lang.String trim(java.lang.String)</function-signature>
    <example>
      Name: ${fn.trim(name)}
    </example>  
  </function>

</taglib>

 

 

我们自己定义一个函数类并写自己的tld即可。

步骤如下:

1.建立自己的类及方法。方法是public static类型的。

package com.lwf.struts.fn;

public class DefineFunction {

	public static String addString(String str){
		return "hello string:" + str;
	}
}

 

2、创建tld文件并拷贝到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>define</description>
  <display-name>define functions</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>fndef</short-name>
  <uri>http://lwf.com/jstl/fun</uri>

  <function>
    <description>
      define
    </description>
    <name>addString</name>
    <function-class>com.lwf.struts.fn.DefineFunction</function-class>
    <function-signature>java.lang.String addString(java.lang.String)</function-signature>
    <example>
      &lt;${fn:addString(str)}
    </example>
  </function>
</taglib>

 

3、在页面中包含。

<%@ taglib prefix="fndef" uri="http://lwf.com/jstl/fun" %>

 

4、使用。

${fndef:addString("ddddd") }

 

5、重启服务器

结果:

hello string:ddddd

可以看到我们的addString方法在输入参数前加了hello string:字符串。

 

附件里面已有下载的jstl库lib和源码

 

你可能感兴趣的:(java,apache,xml,jsp,sun)