自定义标签

自定义标签  


    step1,写一个java类,继承SimpleTagSupport类。


    step2,override doTag方法,在该方法里面编写处理逻辑。


    step3,描述标签(.tld文件)。

        注:

            a. tld文件要放到WEB-INF\下。

            b.<body-content>的值可以是

                empty   ---没有标签体。

                scriptless  ---可以有标签体,并且标签体的内容不能够出现java代码(<%  %>,<%=  %>,<%!  %>)。

                JSP        ---可以有标签体,并且标签体的内容可以出现java代码。但是,只有复杂标签技术才支持该值,简单标签技术只支持empty和scriptless。



代码示例:自定义一个可以输出任意行指定字符串的标签

step1:HelloTag.java

step2:override doTag方法

package tag;

import java.io.IOException;

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

/**
 * 标签类
 * 	1.继承SimpleTagSupport类
 *  2.override doTag方法
 *  3.标签有哪些属性,标签类也有要对应的属性
 *    a.要求属性名一致
 *    b.类型要匹配
 *    c.要有对应的set方法。
 *
 */
public class HelloTag extends SimpleTagSupport{
	private String msg;
	private int qty;
	
	public HelloTag(){
		System.out.println("HelloTag的构造器...");
	}
	
	public void setMsg(String msg) {
		System.out.println("setMsg方法..." + msg);
		this.msg = msg;
	}

	public void setQty(int qty) {
		System.out.println("setQty方法..." + qty);
		this.qty = qty;
	}

	@Override
	public void doTag() throws JspException, IOException {
		System.out.println("doTag方法...");
		/*
		 * SimpleTagSupport类提供了一个方法来获得pageContext,
		 * pageContext提供了一些方法来获得所有的隐含对象。
		 */
		PageContext ctx = (PageContext)getJspContext();
		JspWriter out = ctx.getOut();
		for(int i = 0; i < qty; i++){
			  out.println(msg + "<br/>");
		}
	}
	
}


step3:描述文件  mytag.tld

<?xml version="1.0" encoding="UTF-8" ?>

<taglib 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-jsptaglibrary_2_1.xsd"
    version="2.1">
    <description>JSTL 1.1 core library</description>
	  <display-name>JSTL core</display-name>
	  <tlib-version>1.1</tlib-version>
	  <short-name>c1</short-name>
	  <uri>http://www.xiaolong.com/mytag</uri>
	  
	  <tag>
	    <name>hello</name>
	    <tag-class>tag.HelloTag</tag-class>
	    <body-content>empty</body-content>
	     <attribute>
	        <name>msg</name>
	        <required>true</required>
	        <rtexprvalue>false</rtexprvalue>
	    </attribute>
	    <attribute>
	        <name>qty</name>
	        <required>true</required>
	        <rtexprvalue>true</rtexprvalue>
	    </attribute>
	  </tag>
</taglib>


step4:使用 sayHello.jsp

<%@page pageEncoding="utf-8" contentType="text/html; charset=utf-8" %>
<%@taglib uri="http://www.xiaolong.com/mytag" prefix="c1" %>
<html>
	<head></head>
	<body>
		<c1:hello msg="hello 签下了" qty="${1+4}"/>
	</body>
</html>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值