jsp自定义标签简单应用实例



jsp自定义标签简单应用实例,自定义标签使用演示。jsp自定义标签使用方法步骤。

jsp_tag.jsp文件:

<%@ page language=”java” import=”java.util.*” pageEncoding=”utf-8″%>
<%@ taglib prefix=”usetag” uri=”/WEB-INF/jsp2-function-taglib.tld” %>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<title>My JSP ‘jsp_tag.jsp’ starting page</title>
</head>
<body>
<h1>SimpleTag应用</h1>
<hr>
<br>
<b><u>运行结果:</u></b>
<br>
<usetag:repeat num = “4″>
第${count }次调用<br>
</usetag:repeat>
</body>
</html>

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>
<tag>
<description>This is ‘num’ times </description>
<name>repeat</name>
<tag-class>com.cn.smipleTag.UseSimpleTag</tag-class>
<body-content>scriptless</body-content>
<!– 声明一个变量 –>
<varriable>
<description>The count(1 to 10)</description>
<name-given>count</name-given>
</varriable>
<!– 声明一个属性 –>
<attribute>
<name>num</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>

UseSimpleTag.java文件:

package com.cn.smipleTag;


import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
* SimpleTag处理器,它接受一个num属性,并调用标签体num对应的次数
*
*/

public class UseSimpleTag extends SimpleTagSupport{
private int num;

public void doTag() throws JspException, IOException {
for (int i = 0; i < num; i++) {
getJspContext().setAttribute(“count”, String.valueOf(i+1));
getJspBody().invoke(null);
}
super.doTag();
}
public void setNum(int num) {
this.num = num;
}
}

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>