1.編寫Java類
public class MathUtils {
/**
* 求百分比,保留到小數點後兩位
* @param num1
* @param num2
* @return
*/
public static String percent(int num1,int num2){
return num2 == 0 ? "-" : (Math.round(num1*10000.0/num2)/100.0 + "%");
}
}
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" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
<description>my functions library</description>
<display-name>JSTLCqs functions</display-name>
<tlib-version>1.0</tlib-version>
<!--隨便寫-->
<short-name>mfn</short-name>
<!--全局唯一即可-->
<uri>http://www.cqs.com/functions</uri>
<function>
<!--隨便寫-->
<name>percent</name>
<!-- Java類 -->
<function-class>com.cqs.common.utils.MathUtils</function-class>
<!--返回類型 方法名 參數類型-->
<function-signature>java.lang.String percent(int,int)</function-signature>
</function>
</taglib>
3.配置WEB.xml
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<jsp-config>
<taglib>
<!-- 配置標籤的引用地址 JSP頁面中引用時使用-->
<taglib-uri>http://www.cqs.com/functions</taglib-uri>
<!-- 配置標籤的TLD文件地址 -->
<taglib-location>/WEB-INF/JSTLCqs/ELCqs.tld</taglib-location>
</taglib>
</jsp-config>
..
/>
4.在JSP頁面中使用
<%@ taglib uri="http://www.cqs.com/functions" prefix="mfn" %>
<input name="percent" id="percent" placeholder="percent" value="${mfn:percent(227, 843)}" />
注意:若使用的是tomcat6那麼到這裏就可以收工了。但是若使用的是tomcat7的話就很坑了
java.lang.IllegalArgumentException: taglib definition not consistent with specification version