###**`简单标签`** ####**`如何写一个简单标签`** step1:写一个java类继承SimpleTagSupport package tag; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.SimpleTagSupport; /** * 继承SimpleTagSupport * 重写override doTag方法 * 标签有哪些属性,标签类也有那些属性类型要匹配 * @author pcc * */ public class HelloTag extends SimpleTagSupport{ private String info; private int qty; public HelloTag() { System.out.println("HelloTag构造器"); } public String getInfo() { return info; } public void setInfo(String info) { System.out.println("setInfo执行了"+info); this.info = info; } public int getQty() { return qty; } public void setQty(int qty) { System.out.println("setQty执行了"+qty); this.qty = qty; } @Override public void doTag() throws JspException, IOException { /* * 通过继承自SimpleTagSupport类提供的方法 * 来获得PageContext对象,该对象提供了一些方法 * 用来获得其他所有隐含对象 */ System.out.println("doTag执行了"); PageContext pc =(PageContext)getJspContext(); for(int i= 0;i<100;i++){ pc.getOut().print(info+"<br>"); } } } step2:编写.tld文件,放在WEB-INF文件夹下 <?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"> <tlib-version>1.0</tlib-version> <short-name>w</short-name> <uri>test</uri> <tag> <description> 循环输出 </description> <name>hello</name> <tag-class>tag.HelloTag</tag-class> <!-- 设置标签体内容 empty:说明该标签没有标签体 scrptless:该标签有标签体,但是不可以出现java代码 JSP:说明该标签有标签体,并且标签体的内容可以是java代码,但是,只有复杂标签技术才支持该值 --> <body-content>empty</body-content> <attribute> <description> 想要循环输出的内容 </description> <name>info</name> <!-- 如果是true此属性是必须的 --> <required>true</required> <!-- 如果该属性等于true,则可以用el表达式来赋值 --> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <description> 次数 </description> <name>qty</name> <!-- 如果是true此属性是必须的 --> <required>true</required> <!-- 如果该属性等于true,则可以用el表达式来赋值 --> <rtexprvalue>true</rtexprvalue> </attribute> </tag> step3:taglib指令,使用标签 <%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib uri="test" prefix="w" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title></title> </head> <body style="font-size:30px"> <w:hello info="hello" qty="100"> </w:hello> </body> </html>
如何写一个简单标签
猜你喜欢
转载自www.cnblogs.com/eason-java/p/9341113.html
今日推荐
周排行