標籤:
有時候會遇到需要在JSP中調用Java方法的情況,這個問題可以通過自訂JSTl標籤的方法解決。
步驟:
1,準備好Java方法,這裡需要注意的是,這個方法必須要是靜態static修飾的
2,建立一個tld檔案,將準備的方法添加到tld檔案中
3,然後就可以在jsp中調用了
下面是我的樣本:
1,java類
package com.wangyin.credit.report.util;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; } } }}
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"> <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>
3,在jsp中調用自訂標籤
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
業務種類資訊:${fn:getMean(‘bussinessType‘,‘1‘)}
(備忘:這裡傳遞參數的時候,單引號,雙引號都可以,1也可以不加引號)
4,然後,如果沒有意外的話,你想要的結果就出現了!
自訂JSTL標籤