JSP自定義方法庫

n672 9年前發布 | 18K 次閱讀 JSP Java開發

如果JSTL的方法庫沒有滿足需要,可以使用自定義方法進行擴展

    public class Function{  
          public static int length(Object obj){  //返回對象的長度  
                 if(obj == null){  
                        return 0;  
                 }  

                 if(obj instanceof StringBuffer){  
                        return lenth(((StringBuffer)obj).toString());  
                 }  

                 if(obj instanceof String){  
                        return ((String)obj).getBytes.length;  
                 }  

                 if(obj instanceof Collection){  
                        return ((Collection)obj).size();  
                 }  
          }  
    }  

配置文件
    <?xml version="1.0" ecoding="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                 web-jsptaglibrary_2_0.xsd  
          version="2.0">  

          <description>custom functionslibrary</description>  
          <display-name>customfunctions</display-name>  
          <tlibversion>1.1</tlibversion>  
          <shortname>function</shortname>  
          <uri>http://www.clf.com/tags</uri>  


          <function>  
                 <description>descriptioncontent </description>  
                 <name>lenth</name>  
                 <function-class>com.chen.Funtion</function-class>  
                 <function-signature>  
                        int length(java.lang.Object)  
                 </function-signature>  
                 <example>  
                        ${fn:length(string)}  
                 </example>  
          <function>  

    </taglib>  

自定義方法的聲明寫在 <function-signature>標記里面,格式為

      返回值 方法名(參數1類型,參數2類型……)

加入有個String型變量,賦值“字符串測試”

在JSP頁面中定義的標簽庫的前綴是“fn”,則用法如下

                    ${fn:length(string)}

這句話就能輸出字符串的長度


 本文由用戶 n672 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!