知识点:
【
在TLD中描述标签属性:
开发带属性的标签:
自定义标签可以定义一个或多个属性,这样,在JSP页面中应用自定义标签时就可以设置这些属性的值,通过这些属性为标签处理器传递参数信息,从而提高标签的灵活性和复用性。
要想让一个自定义标签具有属性,通常需要完成两个任务:
在标签处理器中编写每个属性对应的setter方法
在TLD文件中描术标签的属性
为自定义标签定义属性时,每个属性都必须按照JavaBean的属性命名方式,在标签处理器中定义属性名对应的setter方法,用来接收JSP页面调用自定义标签时传递进来的属性值。 例如属性url,在标签处理器类中就要定义相应的setUrl(String url)方法。
在标签处理器中定义相应的set方法后,JSP引擎在解析执行开始标签前,也就是调用doStartTag方法前,会调用set属性方法,为标签设置属性。
】
实现步骤如下:
第一步:编写标签处理器类tagAttribute继承SimpleTagSupport
public class tagAttribute extends SimpleTagSupport {
 /*
 * JSP支持8种基本数据类型自动转换 ,其他类型使用表达式或java代码
 * 
 * 开发带属性的标签步骤如下
 * 第一:声明属性并且生成setter
 * 第二:在*.tld文件中配置标签属性
 */
 private int count;
 private Date date;
 public void setDate(Date date) {
 this.date = date;
 }
 public void setCount(int count) {
 this.count = count;
 }
 public void doTag() throws JspException, IOException {
 JspFragment body=getJspBody();
 JspWriter out=getJspContext().getOut();
 for(int i=0;i<count;i++)
 {
 //传入null则默认是输出给浏览器
 body.invoke(null);
// body.invoke(out);
 }
 String str=date.toLocaleString();
 out.write(str);
 super.doTag();
 }
}
第二步:编写*.tld文件 --->view.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>A tag library exercising SimpleTag handlers.</description>
 <tlib-version>1.0</tlib-version>
 <short-name>SimpleTagLibrary</short-name>
 <uri>http://www.liyong.simpletagattribute</uri>
 <tag>
 <description>show client IP</description>
 <name>attribute</name>
 <tag-class>com.liyong.attribute.tagAttribute</tag-class>
 <!-- 标签体不为空 这与传统标签不同 JSP -->
 <body-content>scriptless</body-content>
 <attribute>
 <!-- 属性名 -->
 <name>count</name>
 <!-- 是否是必须的 -->
 <required>true</required>
 <!-- 是否支持表达式 -->
 <rtexprvalue>true</rtexprvalue>
 </attribute>
 <attribute>
 <!-- 属性名 -->
 <name>date</name>
 <!-- 是否是必须的 -->
 <required>true</required>
 <!-- 是否支持表达式 -->
 <rtexprvalue>true</rtexprvalue>
 </attribute>
 </tag>
</taglib>
第三步:编写jsp 并导入 viewid.tld文件
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.liyong.simpletagattribute" prefix="attribute" %>
<%
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 'simpletag.jsp' starting page</title>
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 </head>
 <body>
<!-- 带属性的标签,这里不是基本数据类型必须通过java代码或是EL表达式-->
<attribute:attribute count="30" date="<%= new Date() %>">
 aaaaaaaaaaaaa
</attribute:attribute>
 </body>
</html>
第四步:测试...
                










