jsp自定义标签实例源码



jsp自定义标签实例介绍。简单的自定义标签应用。

jsp2.0_el.jsp文件源码:

<%@ page language=”java” pageEncoding=”utf-8″%>
<%@ taglib prefix=”el” uri=”/jsp2-example-taglib”%>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<title>My JSP ‘jsp2.0_el.jsp’ starting page</title>
</head>
<body>
<%response.setCharacterEncoding(“utf-8″); %>
<form action=”jsp2.0_el.jsp” method=”get”>
String num1=<input type=”text” name=”x” value=”${el:add(param["x"],”")}”>
<br>
String num2=<input type=”text” name=”y” value=”${el:add(param["y"],”")}”>
<input type=”submit” value=”相加”>
</form>
<p>
结果是:${el:add(param["x"],param["y"]) }
</body>
</html>

JSP_Sum.java源码:

package com.cn.sum;

public class JSP_Sum {
public static int add(String x,String y){
int a = 0;
int b =0;
try {
a=Integer.parseInt(x);
b=Integer.parseInt(y);
} catch (NumberFormatException e) {
System.out.println(“程序运行错误”);
}
return a+b;
}

}


jsp2-function-taglib.tld文件:

<?xml version=”1.0″ encoding=”utf-8″ ?>
<taglib version=”2.0″
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 web-jsptaglibrary_2_0.xsd”>

<tlib-version>1.0</tlib-version>
<short-name>jsp2.0-example-taglib</short-name>
<uri>/jsp2-example-taglib</uri>

<!– 定义JSP2.0函数 –>
<function>
<description>Add x and y</description>
<name>add</name>
<!– 函数所在的类 –>
<function-class>com.cn.sum.JSP_Sum</function-class>
<!– 函数的声明 –>
<function-signature>int add(java.lang.String,java.lang.String)</function-signature>
</function>
</taglib>

web.xml文件:

<?xml version=”1.0″ encoding=”UTF-8″?>
<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>
<taglib-uri>/jsp2-example-taglib</taglib-uri>
<taglib-location>jsp2-function-taglib.tld</taglib-location>
</taglib>
</jsp-config>

</web-app>