使用自定義tld標簽簡化jsp的繁瑣操作


  最近做一個樹形結構的展示,請求目標頁面后,后台只返回簡單的List,雖然有想過在jsp頁面內做一些操作簡化,但是太繁瑣了,其他的標簽又不能滿足需求,所以只能自己做一個。使用tld標簽可以簡化jsp代碼,以后也可以重用代碼,所以出於這兩個優點,用自定義的tld標簽是一個不錯的選擇。這里只做一個簡單例子,將字符串全部變成大寫。

1、定義tld的類 

定義的方法應該是static方法。

public class TestFunction {
    
    public static String stringUpperCase(String target){
        return target.toUpperCase();
    }
} 

2、添加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>fu</short-name>  
  <uri>/WEB-INF/tags/function.tld</uri> 
  
  <function>  
    <name>stringUpperCase</name>  
    <function-class>test.tld.TestFunction</function-class>  
    <function-signature>java.lang.String stringUpperCase(java.lang.String)</function-signature>  
  </function>  
</taglib>  

<short-name>表示聲明標簽的調用名稱。   

<uri>表示tld標簽的位置,tld標簽應該定義在WEB-INF中。這里我放在WEB-INF的tags文件夾中。

<function-class>tld標簽運行的方法的類。

<function-signature>聲明了方法返回的類型,方法名,方法的參數。方法參數可以是List,int等。

 

3、web.xml中聲明tld標簽

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name></display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <jsp-config>  
    <taglib>  
        <taglib-uri>/tags/function</taglib-uri>  
        <taglib-location>/WEB-INF/tags/function.tld</taglib-location>  
    </taglib>  
  </jsp-config> 
</web-app>

4、使用自定義tld標簽

<%@ taglib prefix="fn" uri="/tags/function" %>

${fn:stringUpperCase(target) }

聲明tld標簽后,才開始使用。target是后台保存在request或session的字符串。

 

5、總結

好好使用tld標簽能在關鍵時候使你的頁面更加優雅,在多次使用某段jsp的代碼,可以封裝起來,使頁面更加簡潔,下次再次使用的時候更加方便。

 

    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM