自定義JSTL標簽


有時候會遇到需要在JSP中調用Java方法的情況,這個問題可以通過自定義JSTl標簽的方法解決。

步驟:

  1,准備好Java方法,這里需要注意的是,這個方法必須要是靜態static修飾的

  2,創建一個tld文件,將准備的方法添加到tld文件中,然后將tld映射添加到web.xml文件中

  3,然后就可以在jsp中調用了

 

下面是我的示例:

  1,java類

public class DataDictionaryUtil {

    public static String getMean(String type,String num){
        
        if ("bussinessType".equals(type)) {
            //業務種類
            if ("1".equals(type)) {
                return "貸款";
            }else if("2".equals(type)){
                return "信用卡";
            }else{
                return null;
            }
        }
    return null;
    }

}

 

  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>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>
      <name>getMean</name>
      <function-class>com.wangyin.credit.report.util.DataDictionaryUtil</function-class>
      <function-signature>java.lang.String getMean(java.lang.String,java.lang.String)</function-signature>
      <example>${fn.getMean(type,code)}</example>
  </function>

</taglib>

  

  web.xml文件映射配置(配置在根標簽下)

<jsp-config>
    <taglib>
        <taglib-uri>/credit</taglib-uri>
        <taglib-location>/WEB-INF/dtl/credit.tld</taglib-location>
    </taglib>
</jsp-config>

 

  3,在jsp中調用自定義標簽

  •  先將自定義標簽進行引入
<%@ taglib prefix="credit" uri="/credit" %> 
  • 然后在頁面中進行調用
業務種類信息:${credit:getMean('bussinessType','1')}

(備注:這里傳遞參數的時候,單引號,雙引號都可以,1也可以不加引號)

  4,然后,如果沒有意外的話,你想要的結果就出現了!


免責聲明!

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



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