`

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和源码

 

分享到:
评论

相关推荐

    JSTL 开发自定义标签使用的jar

    JSTL主要包含核心标签库(Core)、XML处理标签库(XML)、函数库(Functions)和JDBC标签库(JDBC)。在这个场景中,我们重点关注的是JSTL的核心标签库以及如何使用自定义标签。 `jstl.jar`是JSTL的核心库,包含了...

    jstl自定义标签和函数思维导图

    jstl自定义标签和函数思维导图

    java自定义标签、自定义函数、taglib

    -- 使用自定义函数库 --&gt; ``` 至于`taglib`,它是Java Web应用中用来定义和管理自定义标签和函数的机制。TLD文件就是taglib的一部分,它提供了标签库的元数据,使得IDE和服务器能够识别并正确处理自定义标签和函数...

    自定义标签和自定义jstl函数的具体项目实现

    引入函数库,然后在EL表达式中调用自定义函数。 ```jsp &lt;%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %&gt; &lt;%@ taglib prefix="myfn" uri="http://example.com/fn" %&gt; ... ${myfn:...

    jstl标签库与使用教程

    **JSTL(JavaServer Pages Standard Tag Library)标签库**是Java Web开发中不可或缺的一部分,它为JSP页面提供了一套标准的标签,用于简化HTML和XML文档的处理,提高代码的可读性和可维护性。JSTL的使用极大地减少...

    jsp2.0 自定义标签和自定标签函数

    - 注册函数库:在web.xml中声明函数库的位置。 2. **使用自定义标签函数** 在JSP页面的EL表达式中,可以直接调用自定义函数,如`${myFunction('参数')}`。 **三、示例解析** "jsp 2.0自定义标签.doc"文件很可能...

    jstl自定义函数[文].pdf

    2. **编写TLD文件**:TLD(Tag Library Descriptor)文件是描述你的自定义函数库的XML文件。在这个文件中,你需要指定函数的URI(Uniform Resource Identifier),这将帮助JSP找到你的TLD文件。此外,你还需要定义`...

    JSTL标签库jar包文件

    每个`taglib`元素定义了一个TLD(Tag Library Descriptor)文件的位置,这告诉服务器JSTL标签库的位置和元数据。 总之,JSTL通过提供丰富的标签来增强JSP页面的功能,而解决"无法解析绝对uri"的错误通常涉及到正确...

    jstl标签库jar包

    **JSTL标签库与JAR包详解** JavaServer Pages Standard Tag Library(JSTL)是Java EE领域中用于简化JSP开发的一个重要工具。它提供了一组预定义的标签,帮助开发者更高效地处理常见任务,如迭代、条件判断、国际化...

    jstl两个核心包和jstl标签库EL表达式详解

    JSTL标签库:** JSTL标签库是预定义的一组标签,它们为JSP开发提供了方便。以下是一些主要的JSTL标签: - **&lt;c:if&gt; 和 &lt;c:choose&gt;**:用于条件判断,类似Java中的if-else语句。 - **&lt;c:forEach&gt;**:用于遍历集合...

    JSTL标签库

    【JSTL标签库】是Java服务器页面(JSP)中的一种重要工具,它旨在增强HTML表单的功能,规范自定义标签的使用,以适应软件开发的分层设计原则,避免在JSP页面中混杂Java逻辑代码。JSTL(JavaServer Pages Standard ...

    JSTL标签库_资料下载.zip

    综上所述,JSTL标签库是Java Web开发中一个非常重要的工具,它提高了代码的可读性和可维护性,降低了视图层的复杂度。通过掌握JSTL,开发者可以更高效地构建动态Web页面,提升开发效率。在提供的“JSTL标签库_资料...

    自定义JSTL

    2. **在JSP中引用**:在JSP页面中引入自定义标签库: ```jsp &lt;%@ taglib prefix="my" uri="http://example.com/mytags" %&gt; ``` 3. **使用自定义标签**:在JSP页面中使用自定义标签: ```jsp &lt;my:greeting name...

    JSP标签、自定义标签,含有属性

    JSTL是一组符合JSR-52标准的标签库,包括核心标签、XML标签、SQL标签、函数标签等。例如,`&lt;c:forEach&gt;`用于循环遍历集合,`&lt;c:if&gt;`用于条件判断,`&lt;fmt:formatDate&gt;`用于日期格式化。这些标签提供了比脚本元素更...

    自定义标签库

    - **TLD (Tag Library Descriptor)**: TLD文件是自定义标签库的元数据,它描述了标签库中的每个标签、属性、变量和函数。TLD通常以`.tld`为扩展名,并且必须放在WEB-INF目录下。 - **标签处理类 (Tag Handler ...

    jstl标签库.rar

    5. **Function**: 提供一些自定义函数,可以扩展标签库的功能。 在IDEA中配置JSTL,我们需要以下步骤: 1. **下载JSTL库**:首先,你需要从官方网站或者Maven仓库下载jstl.jar和standard.jar这两个文件,它们是...

    jstl标签包,用于jsp自定义标签

    在"jstl标签包"中,我们主要关注的是两个关键的组件:jstl.jar和standard.jar。 **jstl.jar** 是JSTL的主要库文件,包含了JSTL核心标签库。这个库提供了如条件语句(if/else)、迭代(foreach)、函数调用等功能,...

    jstl标签库依赖tld文件和jar

    **JSTL标签库**全称为JavaServer Pages Standard Tag Library,是Java服务器页面标准标签库,它提供了一系列的标签来简化JSP开发,使得开发者能够更有效地处理常见任务,如迭代、条件判断、导出数据等。JSTL的核心...

Global site tag (gtag.js) - Google Analytics