步骤如下:
1、创建一个函数库类,里面的方法就是标签函数库要调用的方法(必须是静态方法)
package com.mdd.tag;
public class JiSuan {
//两个数相加
public static double add(double num1,double num2){
return num1+num2;
}
}
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">
<!-- 整个标签的名字 -->
<display-name>myTag</display-name>
<tlib-version>1.0</tlib-version>
<short-name>myTag</short-name>
<!-- 导入标签时的uri -->
<uri>http://mdd/jsp/jstl/functions</uri>
<function>
<!-- 函数名 -->
<name>add</name>
<!-- 自定义的函数的全类名 -->
<function-class>com.mdd.tag.JiSuan</function-class>
<!-- 描述方法,主要通过返回参数类型,方法签名,和方法名;注意,String类型及引用型变量要写全类型 基本数据类型则不需要 -->
<function-signature>double add(double,double)</function-signature>
<example>
Product name: ${mdd.add(a,b)}
</example>
</function>
</taglib>
3、在使用到自定义的函数页面导入标签,并使用
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="myTag" uri="http://mdd/jsp/jstl/functions" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
${myTag:add(1,2)}
</body>
</html>